asp.net-mvc - 如何在 mvc 中动态显示模型的属性?

标签 asp.net-mvc asp.net-mvc-4

现在,如果我知道模型的名称和值,就可以显示和更新模型。例如,这是我的学生模型:

public class Student
{
    public string Name { get; set; }
    public bool Sex { get; set; }
    public bool Address { get; set; }
}

而且,这是我在 View 中的内容:

@Html.TextBoxFor(model => model.Name)
@Html.TextBoxFor(model => model.Sex)
@Html.TextBoxFor(model => model.Address)

我想显示和更新一个模型,但我不知道它有多少属性以及它们的名称和值是什么。例如,如果我将 Fruit 模型返回到 View ,我将需要显示和更新它的属性,如价格或重量。如果我返回一个 Student 模型,我将需要显示和更新 Name、Sex 和 Address 等属性。我的项目中有十多个模型。我的老板说我可以使用像 Dictionary<string,string> 这样的键和值这样,并遍历模型属性,但我不知道该怎么做。

最佳答案

这是一个简单的示例,展示了如何使用动态模型执行此操作。

首先,我设置了几个类来表示您在上面提供的不同模型示例:

public class Student
{
    public string Name { get; set; }
    public string Sex { get; set; }
    public string Address { get; set; }
}

public class Fruit
{
    public decimal Price { get; set; }
    public decimal Weight { get; set; }
}

接下来,我为每种类型创建了一个 DisplayTemplate,如下所示:

@model Fruit

<p>Fruit template</p>

@Html.DisplayFor(m => m.Price)
@Html.DisplayFor(m => m.Weight)

@model Student

<p>Student template</p>

@Html.DisplayFor(m => m.Name)
@Html.DisplayFor(m => m.Sex)
@Html.DisplayFor(m => m.Address)

现在是有趣的部分。我创建了一个 View 模型来保存动态模型,同时还提供了一个字段来获取模型的基础类型:

public class ViewModel
{
    public dynamic Model { get; set; }
    public Type ModelType { get; set; }
}

这让我们可以做两件事:

  1. 将任意类型分配给 Model
  2. 使用 ModelType 作为控制应为模型调用哪个 DisplayTemplate 的方法。

因此,您的 View 将如下所示:

@model ViewModel

@Html.DisplayFor(m => m.Model, Model.ModelType.ToString())

如您所见,Html.DisplayFor 的重载允许我们指定模板名称,这就是第二个参数所代表的内容。

最后,我创建了一个快速操作方法来对此进行测试。

首先,对于 Student 类型:

public ActionResult Index()
{
    var model = new ViewModel();
    model.ModelType = typeof(Student);
    model.Model = new Student { Name = "John", Sex = "Male", Address = "asdf" };

    return View(model);
}

其次,对于 Fruit 类型:

public ActionResult Index()
{
    var model = new ViewModel();
    model.ModelType = typeof(Fruit);
    model.Model = new Fruit { Price = 5, Weight = 10 };

    return View(model);
}

两者都给出了所需的输出。

关于asp.net-mvc - 如何在 mvc 中动态显示模型的属性?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18516230/

相关文章:

jquery - 使用 asp.net mvc 中的单选按钮进行远程验证

c# - 集成测试数据库,我做对了吗?

javascript - 检查 AngularJS 模块是否被引导

c# - ModelState.IsValid = false MVC 4 Entity Framework

asp.net-mvc - MVC session 到期但未进行身份验证

javascript - 如何停止允许或阻止减号多次输入文本框?

c# - Asp.Net Mvc4 : How to use @ character in js file

razor - 在 Razor 助手方法中添加非中断空间

javascript - 使用 Asp.Net mvc4 在 FullCalendar 中加载事件

c# - 如何在同一 View 中使用两个从两个不同模型创建的 ActionResult?