![](/img/trans.png)
[英]Dropdown list is not retaining the selected value after submitting the form in Asp.net core Mvc
[英]Set selected index of dropdown to zero after form submit in ASP.NET MVC
我对新的asp.net mvc和使用aps.net mvc 5有所了解。我在aps.net mvc中使用html helper创建了以下下拉列表。 当我提交(发回)表格时,我想将所选索引设置为零。 在这里,我使用的是optionLabel“ --select--”。 我想在回发后将所选值设置为那个值(“ --select--”)。 如何实现这一目标。 请帮忙。 谢谢。
@Html.DropDownListFor(model => model.TestCategory, new SelectList(@ViewBag.TestCategories, "value", "text"), "-- Select --", new { @class = "form-control input-sm"})
控制器代码
[HttpGet]
public ActionResult Index()
{
var model = new LaboratoryViewModel {
medicaltestlist = new List<MedicalTest>()
};
PopTestCategory();
PopEmptyDropdown();
return View(model);
}
[HttpPost]
public ActionResult Index(LaboratoryViewModel labvm)
{
var test = PopMedicalTests().Where(x => x.TestSerial == Convert.ToInt32(labvm.TestCode)).FirstOrDefault();
if (labvm.medicaltestlist == null)
labvm.medicaltestlist = new List<MedicalTest>();
if(!labvm.medicaltestlist.Any(x=> x.TestSerial == test.TestSerial))
labvm.medicaltestlist.Add(test);
labvm.TestCategory = "";
PopTestCategory();
return View(labvm);
}
public void PopTestCategory()
{
var categorylist = new List<DropDownItem>
{
new DropDownItem{value="Medical",text="Medical"},
new DropDownItem{value="Animal",text="Animal"},
new DropDownItem{value="Food",text="Food"},
new DropDownItem{value="Water",text="Water"}
};
ViewBag.TestCategories = categorylist;
}
public class DropDownItem
{
public int id { get; set; }
public string value { get; set; }
public string text { get; set; }
}
您在post方法中返回视图,因此,如果您选择(例如) Animal
则在返回视图时将选择该值,因为html助手使用的是ModelState
而不是model属性的值。 设置labvm.TestCategory = "";
没有效果。 正确的方法是遵循PRG模式并重定向到GET方法,但是可以通过调用ModelState.Clear();
来完成此工作ModelState.Clear();
在设置重置TestCategory
的值之前,尽管这样做会清除所有ModelState
属性和错误,并且可能会有其他副作用。
旁注:您不需要DropDownItem
类。 MVC已经有一个设计用于下拉列表的SelectListItem
类,在任何情况下,您都可以将PopEmptyDropdown()
方法中的所有代码替换为
ViewBag.TestCategories = new SelectList(new List<string>() { "Medical", "Animal", "Food", "Water" });
并认为
@Html.DropDownListFor(m => m.TestCategory, (SelectList)@ViewBag.TestCategories, "-- Select --", new { @class = "form-control input-sm"})
如果将下拉列表中顶部项目的“值”属性设置为某种值,然后将包含绑定属性的模型传递回模型,则该模型应该起作用?
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.