所以我创建了一个下拉列表,我根据列表中的选定值更改了语言,但是当它提交时我松开了所选的值并重置了。有什么方法可以记住我提交时所选择的内容吗?
@using (Html.BeginForm("SetCulture", "Home", new { @onsubmit = @"$(#Languages option:selected).text();" }))
@Html.DropDownList("Languages", Test.Configuration.GetLanguages().Select(x => new SelectListItem() { Text = x.Text, Value = x.Value }), new{@onchange = @"$(form).submit();"})
答案 0 :(得分:0)
您应该使用语法
@Html.DropDownListFor(model => model.Language, new SelectList(Test.Configuration.GetLanguages().Select(x => new SelectListItem() { Text = x.Text, Value = x.Value })))
然后MVC知道使用该字段存储下拉列表中的所选选项。
根据下面的评论,这就是我在模型中声明语言的方式:
PageViewModel.cs
public class PageViewModel {
...
public string Language { get; set; }
public SelectList Languages { get; set; }
}
HomeController.cs
public ActionResult Index(PageViewModel pageViewModel)
{
//put breakpoint on the return view and after you submit a selection you'll see that the pageViewModel argument has the language of what you selected
return View(new PageViewModel
{
Language = "English",
Languages = new SelectList(new List<string>
{
"English",
"Danish",
"Spanish",
"French"
})
});
}
Index.cshtml
@model MvcPlayground.Controllers.PageViewModel
<h2>Languages!</h2>
@using (Html.BeginForm())
{
@Html.DropDownListFor(model => model.Language, Model.Languages)
<input type="submit"/>
}
MVC将使用language属性来确定回发中的所选项目,只要您正确传递它。
答案 1 :(得分:0)
您可以像这样更改代码
public ActionResult Index()
{
//pass the Enumerable<SelectListItem> in to viewbag
ViewBag.Countrys = new List<SelectListItem>{
new SelectListItem { Selected = true, Text = "-Select-", Value = "-1"},
new SelectListItem { Text = "India", Value = "100"},
new SelectListItem { Text = "US", Value = "101"},
};
return View();
}
你需要一个像这样的模型
public class HomeModel
{
public string FirstName { get; set; }
public int CountryId { get; set; }
}
然后在视图中
@model Stratergy.Models.Home.HomeModel
@using (@Html.BeginForm("YourAction", "your controller"))
{
<fieldset>
<legend>Personal Form:</legend>
@Html.TextBoxFor(model=>model.FirstName)
@Html.DropDownListFor(model=>model.CountryId,(IEnumerable<SelectListItem>)@ViewBag.Countrys)
<input type="submit" value="Finish" />
</fieldset>
}
当formpost
时,您可以在模型中获取所选值 [HttpPost]
public ActionResult YourAction(HomeModel homeModel)
{
return Json(new { Result = "OK"});
}