使用下拉列表中的动态值设置属性

问题描述:

这里我想在MVC中的HttpPost之后单击它时,在动态下拉列表中选择一个属性“选择”,它显示相同的第一个文本“请选择一个类别”。使用下拉列表中的动态值设置属性

@if (Model.objlist1.Count != 0) { 
    <select id="catID" onchange="getID();this.form.submit();"> 
     <option id="removeIT" value="007">Please select a category</option> 
     @foreach (var item in Model.objlist1) { 
      //a++; 
      <option value="@item.categoryID">@item.category</option> 
     } 
    </select> 
    @Html.HiddenFor(m => m.categoryID, new { @id = "newCatID", @name = "newCatID" }) 
} 

从HttpPost我想用价值来检查和选项标签“中选择”设置属性以获得在动态降“选择”属性foreach循环选项标签内上下重装后。

尝试这样 在后端通过类别

ViewData["category"] = new SelectList(
new List<SelectListItem> 
{ 
    new SelectListItem { Text = "Cat1", Value = 1}, 
    new SelectListItem { Text = "Cat2", Value = 2}, 
}, "Value" , "Text"); 

在你看来

@Html.DropDownListFor(model => model.categoryID, ViewData["category"] as IEnumerable<SelectListItem>, "Please select a category") 
+0

但我如何能组属性中查看页面“选择”而不是后端类别,因为你可以在上面看到我在选项标签上使用foreach循环,我以这种方式需要它。 –

+0

它将自动选择取决于值 –

+0

问题已解决将选项标记的值添加到viewbag,然后将其设置在$(“#catID”)。val('@ ViewBag.ID')文档就绪函数内 –