MVC 5 单个视图中的多个模型 [英] MVC 5 Multiple Models in a Single View

查看:41
本文介绍了MVC 5 单个视图中的多个模型的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

有人可以提供一个如何在一个视图中组合两个模型的示例吗?

Could somebody please provide an example of how to combine two models within one view?

目前我有一个名为 RecordCard 的页面,其中包含:

Currently I have a page called RecordCard which contains:

@model IEnumerable<WebApplication1.Models.Weight>

这是由 AccountController 中的以下代码提供的:

This is provided by the following code in the AccountController:

public ActionResult RecordCard()
{
    var UserId = User.Identity.GetUserId();
    var weightModel = from m in db.Weights where m.UserId == UserId select m;
    return View(weightModel);
}

RecordCard 页面还包含一个绑定到以下类的表单:

The RecordCard page also contains a form which is bound to the following class:

public class AddWeightModel
{
    [Required]
    [DataType(DataType.Text)]
    [Display(Name = "Stone")]
    public Nullable<short> Stone { get; set; }

    [Required]
    [DataType(DataType.Text)]
    [Display(Name = "Pound")]
    public Nullable<short> Pound { get; set; }
}

但是,这是两个具有不同目的的独立模型,所以我如何组合成一个模型,该模型包含一个 IEnumerable 列表和一组表单元素,这些元素最终将正确发布到 AccountController 以使用以下代码:

However, these are two individual models with different purposes, so how do I combine to a single model that contains an IEnumerable list and set of form elements that will ultimately post to the AccountController correctly to add a record to the database using the following code:

[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult RecordCard(Weight Model)
{
    if (ModelState.IsValid)
    {
        using (WebApplication1Entities db = new WebApplication1Entities())
        {
            Weight weight = new Weight();
            weight.UserId = User.Identity.GetUserId();
            weight.Stone = Model.Stone;
            weight.Pound = Model.Pound;
            weight.Date = System.DateTime.Now;

            db.Weights.Add(Model);
            db.SaveChanges();
        }
    }
    return View(Model);
}

我在下面添加了重量类:

I have included the Weight class below:

public partial class Weight
{
    public int Id { get; set; }
    public string UserId { get; set; }
    public Nullable<short> Stone { get; set; }
    public Nullable<short> Pound { get; set; }
    public Nullable<System.DateTime> Date { get; set; }
}

这里还有 WebApplication1Entities 类,它将权重表声明为权重:

Also here is the WebApplication1Entities class which declares the Weight table as Weights:

public partial class WebApplication1Entities : DbContext
{
    public WebApplication1Entities()
        : base("name=WebApplication1Entities")
    {
    }

    protected override void OnModelCreating(DbModelBuilder modelBuilder)
    {
        throw new UnintentionalCodeFirstException();
    }

    public virtual DbSet<Weight> Weights { get; set; }
}

请解释需要修改的内容以及如何修改,无论我尝试阅读、遵循和实现什么,我似乎都遗漏了一些东西.

Please explain what needs to be modified and how, no matter what I try to read, follow and implement, I seem to be missing something.

任何帮助将不胜感激:-)

Any help would be much appreciated :-)

推荐答案

我以前解决过这个问题,可以得出一个优雅的解决方案.

I've tackled this before, can came to an elegant solution.

首先,您需要设置要发送的主要类,以及用于存储它们以最终发送到 view 的持有者"类.
您可能已经发现,这是因为 view 不能将多个模型发送给它.

First, you'd want to setup your main classes to send, as well as a 'holder' class to store them to eventually send to a view.
As you probably found out, this is because a view can't have multiple models sent to it.

public class WebsiteTheme
{
    public string Color { get;set; }
    public string Title { get;set; }

    public WebsiteTheme() {
         Color = "blue";
         Title = "test website";
    }
}

public class User
{
    public string Name { get;set; }
    public string Gender { get;set; }

    public User() {
         Name = "Anonymous";
         Gender = "Unspecified";
    }
}

public class ToPage
{
    public WebsiteTheme WebsiteTheme{ get; set; }
    public User User { get; set; }

    public ToPage() {
         websiteTheme = new WebsiteTheme();
         user = new User();
    }
}

这将允许您将任意数量的课程发送到您的页面.

This will allow you to send any amount of classes to your page.

然后,在您的控制器中,您需要填充这些类.确保先将它们全部初始化,然后将填充的类设置为您的持有者类.

Then, in your controller, you'd want to populate those classes. Make sure to initialise them all first, then set the populated classes to your holder class.

WebsiteTheme websiteTheme = new WebsiteTheme();
websiteTheme.Color = "orange";

User user = new User();
user.Name = "Darren";

ToPage toPage = new ToPage();
toPage.User = user;
toPage.WebsiteTheme = websiteTheme;

return View(toPage);

在您看来,您可以随意称呼他们.但请确保在每种情况下都使用 HolderModel.SpecifiedModel.

In your view, you'd call them in any way you want to. But make sure to use HolderModel.SpecifiedModel in every case.

@model WebApplication1.Models.ToPage

@Html.DisplayFor(model => model.User.Name)

这篇关于MVC 5 单个视图中的多个模型的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆