c# - 如何在 cshtml(razor)上设置属性?

标签 c# .net asp.net-mvc asp.net-mvc-3 razor

我想根据我的后端数据设置“已选择”选项。这是我的代码示例...

<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 = "&quot;selected&quot;"); }>@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/

相关文章:

c# - XML 序列化 - 大数据(20GB),OutOfMemoryException

c# - 在 PushSharp 4.0 中构建 GCM 消息

c# - 在叠加视频(VLC Winform)上绘制透明控件(文本)

c# - 图片上传不损失质量

c# - C#调用AS400程序,从QTEMP中选择文件

javascript - 如何在 AngularJS 中实现服务器端搜索框

c# - Oracle 数据访问 ORA-06512 : character string buffer too small

c# - 获取别名列总和的 SQL 子查询

c# - Generic 类型参数前的 "out"是什么意思?

asp.net-mvc - 不要缩小ASP .NET MVC 4 BundleConfig中的某些文件