asp.net-mvc – 在ASP.NEt MVC 3中传递Html.BeginForm()中DropDownList的SelectedValue

这是我的查看代码
@using(Html.BeginForm(new { SelectedId = /*SelectedValue of DropDown*/ })) {

 <fieldset>

     <dl>
       <dt>
           @Html.Label(Model.Category)
       </dt>
       <dd>
        @Html.DropDownListFor(model => Model.Category,CategoryList)
       </dd>
    </dl>

 </fieldset>
 <input type="submit" value="Search" />


}

如图所示,我需要将下拉选择值传递给BeginForm()Html帮助器中的操作.你的建议是什么?

解决方法

提交表单时将传递选定的值,因为下拉列表由< select>表示.元件.您只需调整视图模型,使其具有名为SelectedId的属性,例如,您将绑定下拉列表:
@using(Html.BeginForm() )
{
    <fieldset>
        <dl>
            <dt>
                @Html.LabelFor(x => x.SelectedId)
            </dt>
           <dd>
                @Html.DropDownListFor(x => x.SelectedId,Model.CategoryList)
           </dd>
        </dl>
    </fieldset>

    <input type="submit" value="Search" />
}

这假定以下视图模型:

public class Myviewmodel
{
    [displayName("Select a category")]
    public int SelectedId { get; set; }

    public IEnumerable<SelectListItem> CategoryList { get; set; }
}

将由您的控制器处理:

public ActionResult Index()
{
    var model = new Myviewmodel();
    // Todo: this list probably comes from a repository or something
    model.CategoryList = new[]
    {
        new SelectListItem { Value = "1",Text = "category 1" },new SelectListItem { Value = "2",Text = "category 2" },new SelectListItem { Value = "3",Text = "category 3" },};
    return View(model);
}

[HttpPost]
public ActionResult Index(Myviewmodel model)
{
    // here you will get the selected category id in model.SelectedId
    return Content("Thanks for selecting category id: " + model.SelectedId);
}

相关文章

### 创建一个gRPC服务项目(grpc服务端)和一个 webapi项目(...
一、SiganlR 使用的协议类型 1.websocket即时通讯协议 2.Ser...
.Net 6 WebApi 项目 在Linux系统上 打包成Docker镜像,发布为...
一、 PD简介PowerDesigner 是一个集所有现代建模技术于一身的...
一、存储过程 存储过程就像数据库中运行的方法(函数) 优点:...
一、Ueditor的下载 1、百度编辑器下载地址:http://ueditor....