我想根据我的后端数据设置“已选择”选项。这是我的代码示例...
<select id="listName" name="listName">
<option>Select Name</option>
@foreach (var item in ViewBag.NameList as Dictionary<string, string>)
{
//worked in MVC2, not with razor
<option value= '@item.Key' @if (TempData["name"].ToString() == item.Key) { selected = ""selected""); }>@item.Value - @item.Key</option>
string nameSelect = TempData["name"].ToString() == item.Key ? "selected" : "";
<option value= '@item.Key' selected= '@nameSelect'>@item.Value - @item.Key</option>
}
</select>
有更好的方法吗?
最佳答案
Is there a better way to do this?
哦,该死的。当然使用 View 模型。那么让我们定义一个 View 模型:
public class MyViewModel
{
public string SelectedValue { get; set; }
public IEnumerable<SelectListItem> Values { get; set; }
}
然后是一个 Controller 操作,它将从您的数据源填充此 View 模型:
public ActionResult SomeAction()
{
var model = new MyViewModel();
// preselect an item with Value=2
model.SelectedValue = "2";
// this could of course come from a database or something
model.Values = new[]
{
new SelectListItem { Value = "1", Text = "item 1" },
new SelectListItem { Value = "2", Text = "item 2" },
new SelectListItem { Value = "3", Text = "item 3" },
};
return View(model);
}
最后是相应的强类型 View :
@model MyViewModel
....
@Html.DropDownListFor(x => x.SelectedValue, Model.Values, "Select")
既然你在问题中展示了一些字典,我们可以假设你已经有了这本字典。在您的示例中,您已将其塞入 ViewBag(这是错误的),但您可以将其绑定(bind)到 View 模型:
public ActionResult SomeAction()
{
Dictionary<string, string> values = ......
var model = new MyViewModel();
model.SelectedValue = (string)TempData["name"];
model.Values = values.Select(x => new SelectListItem
{
Value = x.Key,
Text = string.Format("{0} {1}", x.Key, x.Value)
});
return View(model);
}
这就是 ASP.NET MVC:强类型、 View 模型,没有 ViewBag。
关于c# - 如何在 cshtml(razor)上设置属性?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11724456/