Cra*_*aig 14 asp.net-mvc razor asp.net-mvc-3
我正在寻找使用MVC创建下拉列表编辑器模板的最佳方法.似乎有各种各样的方法,但我找不到任何最好的方法,每个人似乎都有不同的方法.我也在使用带有Razor的MVC3,所以首选一种适用于此的方法.
Dar*_*rov 21
有很多方法和说法哪个最好是主观的,可能不适用于你的场景,这是你忘记在你的问题中描述的方式.我是这样做的:
模型:
public class MyViewModel
{
public string SelectedItem { get; set; }
public IEnumerable<Item> Items { get; set; }
}
public class Item
{
public string Value { get; set; }
public string Text { get; set; }
}
Run Code Online (Sandbox Code Playgroud)
控制器:
public class HomeController : Controller
{
public ActionResult Index()
{
var model = new MyViewModel
{
// TODO: Fetch this from a repository
Items = new[]
{
new Item { Value = "1", Text = "item 1" },
new Item { Value = "2", Text = "item 2" },
new Item { Value = "3", Text = "item 3" },
}
};
return View(model);
}
[HttpPost]
public ActionResult Index(MyViewModel model)
{
if (!ModelState.IsValid)
{
// redisplay the view to fix validation errors
return View(model);
}
// TODO: The model is valid here =>
// perform some action using the model.SelectedItem
// and redirect to a success page informing the user
// that everything went fine
return RedirectToAction("Success");
}
}
Run Code Online (Sandbox Code Playgroud)
查看(~/Views/Home/Index.cshtml):
@model MyApp.Models.MyViewModel
@{ Html.BeginForm(); }
@Html.EditorForModel()
<input type="submit" value="OK" />
@{ Html.EndForm(); }
Run Code Online (Sandbox Code Playgroud)
编辑模板(~/Views/Home/EditorTemplates/MyViewModel.cshtml):
@model MyApp.Models.MyViewModel
@Html.DropDownListFor(x => x.SelectedItem,
new SelectList(Model.Items, "Value", "Text"))
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
22037 次 |
| 最近记录: |