繁体   English   中英

如何在mvc中动态显示模型的属性?

[英]How to show the model's attribute dynamically in mvc?

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

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

而且,我的观点中有以下内容:

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

我想显示和更新模型,但我不知道它有多少属性以及它们的名称和值是什么。 例如,如果我将Fruit模型返回到视图,我将需要显示和更新其属性,如价格或重量。 如果我返回学生模型,我将需要显示和更新名称,性别和地址等属性。 我的项目中有十多个模型。 我的老板说我可以像这样使用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)

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

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

这允许我们做两件事:

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

因此,您的视图将如下所示:

@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);
}

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM