简体   繁体   English

如果不使用 ViewModel object,一个 Razor 视图是否可以拥有多个 model?

[英]Can a Razor view have more than one model without using a ViewModel object?

@model MyMVC.Models.MyMVC.MyModel

@{
    ViewBag.Title = "Index";
}

The reason why I ask this question is in MVC we can have more than 1 form, so I would like to have a model for each form.我问这个问题的原因是在 MVC 中我们可以有不止一种形式,所以我想每个形式都有一个 model。 But when I was trying to add another model at the top of the view, it displays an error.但是当我试图在视图顶部添加另一个 model 时,它显示错误。 I know we can use ViewModel which has model1 and model2 inside, but it's not the question I am asking.我知道我们可以使用内部有 model1 和 model2 的ViewModel ,但这不是我要问的问题。

I just simply want to know is there any way that we can put in 2 models into 1 view.我只是想知道有什么方法可以将 2 个模型放入 1 个视图中。

Update:更新:

For example, I want to have 2 forms in my view, so for each form I'd like to have a separated model.例如,我想在我的视图中有 2 个 forms,所以对于每个表单,我希望有一个单独的 model。

Update 2 Thank you all for your replies.更新 2谢谢大家的回复。 I now know that MVC only supports one single model on one view.我现在知道 MVC 在一个视图上只支持一个 model。 Do you guys consider this a disadvantage of MVC?你们认为这是 MVC 的缺点吗? Why or Why not?(No one has answered it yet.... why?)为什么或为什么不?(还没有人回答......为什么?)

Your answers are similar, so I don't even know which one should be set as an answer.你的答案很相似,所以我什至不知道应该将哪个设置为答案。

You should use some prtialviews for other models.您应该为其他模型使用一些prtialviews。 You have your main view with main model.您拥有主模型的主视图。 Inside of that view, you could have some partialviews with their models and their validations.在那个视图里面,你可以有一些带有模型和验证的局部视图。

--------------------------------------Edit: - - - - - - - - - - - - - - - - - - - 编辑:

As others said it is better to use View Models and combine the models with each others.正如其他人所说,最好使用视图模型并将模型相互组合。 But as you wanted I created a sample project for you on my Github account:但是如您所愿,我在我的 Github 帐户上为您创建了一个示例项目:

https://github.com/bahman616/ASPNET_MVC_multiple_models_in_a_view_with_partialview.git https://github.com/bahman616/ASPNET_MVC_multiple_models_in_a_view_with_partialview.git

Here is the simplified code of that project:这是该项目的简化代码:

Here are two models:这里有两个模型:

public partial class Person
{
    public int ID { get; set; }
    [Required]
    public string Name { get; set; }
}
public partial class Company
{
    public int Id { get; set; }
    [Required]
    public string Name { get; set; }
}

I want to have both create views in one view, so this is the parent view:我想在一个视图中创建两个视图,所以这是父视图:

@model ASP_NET_MVC_Multiple_Models_In_A_View.Models.Person

@{
    ViewBag.Title = "Create";
}

<h2>Create</h2>

@using (Html.BeginForm("Create","Person")) {
    @Html.ValidationSummary(true)

    <fieldset>
        <legend>Person</legend>

        <div class="editor-label">
            @Html.LabelFor(model => model.Name)
        </div>
        <div class="editor-field">
            @Html.EditorFor(model => model.Name)
            @Html.ValidationMessageFor(model => model.Name)
        </div>

        <p>
            <input type="submit" value="Create" />
        </p>
    </fieldset>
}

<div>
    @Html.ActionLink("Back to List", "Index")
</div>

@{Html.RenderAction("_CompanyCreate", "Company");}

@section Scripts {
    @Scripts.Render("~/bundles/jqueryval")
}

And this is the partial view:这是部分观点:

@model ASP_NET_MVC_Multiple_Models_In_A_View.Models.Company

<script src="~/Scripts/jquery-1.7.1.min.js"></script>
<script src="~/Scripts/jquery.validate.min.js"></script>
<script src="~/Scripts/jquery.validate.unobtrusive.min.js"></script>

@using (Html.BeginForm("_CompanyCreate","Company")) {
    @Html.ValidationSummary(true)

    <fieldset>
        <legend>Company</legend>

        <div class="editor-label">
            @Html.LabelFor(model => model.Name)
        </div>
        <div class="editor-field">
            @Html.EditorFor(model => model.Name)
            @Html.ValidationMessageFor(model => model.Name)
        </div>

        <p>
            <input type="submit" value="Create" />
        </p>
    </fieldset>
}

<div>
    @Html.ActionLink("Back to List", "Index")
</div>

Simple answer: No, you can't have two models.简单的回答:不,你不能有两个模型。

Details There is only one way to declare a Model to be used by a view:详细信息只有一种方法可以声明视图使用的模型:

@model [namespace].[path].[ViewModelName]

There is no way to specify multiple of these above.没有办法在上面指定多个。

In addition to that, you can only send one object to a view from the Controller, which would be the model:除此之外,您只能将一个对象从控制器发送到视图,这将是模型:

public ActionResult WhateverAction()
{
    var model = new MyViewModel();
    return View(model);
}

Theoretically you cant do it because it binds one model to one view.理论上你不能这样做,因为它将一个模型绑定到一个视图。 But you can create somethink like a model helper which combines two other models to one但是你可以像模型助手一样创建一些想法,将其他两个模型组合成一个

public class model1
{
     string var1 {get; set;}
     string var2 {get; set;}
}

public class model2
{
     string var3 {get; set;}
     string var4 {get; set;}
}

public class modelofBoth
{
     model1 mod1 {get; set;}
     model2 mod2 {get; set;}
}

If you cannot/don't want to modify the model passed to the view then you could pass the additional object in via the ViewBag object.如果您不能/不想修改传递给视图的模型,那么您可以通过 ViewBag 对象传递附加对象。 It feels like a hack to me but it works:对我来说感觉像是一个黑客,但它有效:

Controller:控制器:

ViewBag["Model2"] = yourObject

View:看法:

@{var Model2 = ViewBag["Model2"] as yourObjectType;}

Technically, you could write your own view engine (derived from the RazorViewEngine?) using a custom WebViewPage and have it do whatever you want.从技术上讲,您可以使用自定义 WebViewPage 编写自己的视图引擎(从 RazorViewEngine 派生?)并让它做任何您想做的事情。 The view derives from WebViewPage<T> where T is the type of the model for the page.视图派生自WebViewPage<T> ,其中T是页面模型的类型。 To support multiple models, the view base class would need to have multiple generic types.为了支持多个模型,视图基类需要有多个泛型类型。 Using the baked in RazorViewEngine, however, you're limited to a single model type per view and much of the controller framework presumes a single model per view so you'd have to rewrite that, too.但是,使用 RazorViewEngine 中的烘焙,您仅限于每个视图的单一模型类型,并且大部分控制器框架假定每个视图只有一个模型,因此您也必须重写它。 There doesn't seem to be much point in that, however, as you could simply have your models be properties of the (single) view model, then use partial views for each of the forms providing the property as the model for the partial.然而,这似乎没有什么意义,因为您可以简单地让您的模型成为(单个)视图模型的属性,然后为每个提供该属性的表单使用局部视图作为局部模型。

For more information see http://haacked.com/archive/2011/02/21/changing-base-type-of-a-razor-view.aspx有关更多信息,请参阅http://haacked.com/archive/2011/02/21/changed-base-type-of-a-razor-view.aspx

Answer is NO.答案是否定的。 Thats why ViewModel pattern Exists.这就是 ViewModel 模式存在的原因。 because the razor engine is totally relied on the model you passed, the model is used for ModelBinding for the basic CRUD Operations.由于剃刀引擎完全依赖于您传递的模型,因此模型用于基本 CRUD 操作的 ModelBinding。

You can easily have 1 model per form.每个表单可以轻松拥有 1 个模型。 For each form, you just have to do something like this:对于每个表单,您只需要执行以下操作:

var model = new MyModel();
@Html.TextBoxFor(m => model.Title)
@Html.ValidationMessageFor(m => model.Title)

The validation works like a charm.验证就像一个魅力。

This way, you can keep your model to display information as usual and have 1 model per form to submit data (for example newsletter subscription)这样,您可以让模型像往常一样显示信息,并且每个表单有 1 个模型来提交数据(例如时事通讯订阅)

if your models are similar, Make a new model contains references to all models you want, and use it.如果您的模型相似,请制作一个新的 model 包含对您想要的所有模型的引用,并使用它。 if models are not similar, you can fill new model with similar fields you need from all your models.如果模型不相似,您可以使用所有模型所需的相似字段填充新的 model。 but if you wants use totally different models, you should use Partial view s.但是如果你想使用完全不同的模型,你应该使用Partial view s。

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

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