Pass SelectedValue of DropDownList in Html.BeginForm() in ASP.NEt MVC 3

≯℡__Kan透↙ 提交于 2019-11-27 22:43:15

问题


This is my View Code:

@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" />


}

As code shown I need to pass the dropdown selected value to the action in BeginForm() Html helper. What is your suggestion?


回答1:


The selected value will be passed when the form is submitted because the dropdown list is represented by a <select> element. You just need to adapt your view model so that it has a property called SelectedId for example to which you will bind the dropdown:

@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" />
}

This assumes the following view model:

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

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

that will be handled by your controller:

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);
}


来源:https://stackoverflow.com/questions/10187469/pass-selectedvalue-of-dropdownlist-in-html-beginform-in-asp-net-mvc-3

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!