简体   繁体   English

ASP.NET MVC LIST和Create在同一视图中

[英]ASP.NET MVC LIST and Create in same view

Ok I have a View thats is strongly typed as a collection of MyObject 好的我有一个View强制类型作为MyObject的集合

@model IEnumerable<ViewModels.MyObject>

I loop through the collection to create a list of the objects. 我遍历集合以创建对象列表。

On the same page I need to create form to add a new MyObject. 在同一页面上,我需要创建表单来添加新的MyObject。

Is there a way to use Html helpers along wih lambda expressions to create elements strongly typed from my model? 有没有办法沿着lambda表达式使用Html帮助器来创建从我的模型强类型的元素?

or would it be best to load the Form portion of this page as another partial view typed as MyObject(not a collection)? 或者最好将此页面的Form部分加载为另一个部分视图,类型为MyObject(不是集合)?

You can create view model with two view models as properties: 您可以使用两个视图模型创建视图模型作为属性:

class ListCreateViewModel {
    ListViewModel ListViewModel { get; set; }
    CreateViewModel CreateViewModel { get; set; }
}

Then you can use 然后你可以使用

Html.RenderPartial("Create", Model.CreateViewModel);

Your partial will have CreateViewModel as model. 您的部分将CreateViewModel作为模型。

You can also make totally separate view and model and call: 您还可以制作完全独立的视图和模型并调用:

Html.RenderAction("Create", "Controller");

RenderAction behaves as new request and view is rendered in different context. RenderAction表现为新请求,视图在不同的上下文中呈现。

I loop through the collection to create a list of the objects. 我遍历集合以创建对象列表。

Why do you loop? 你为什么要循环? Looping in a view is ugly. 在一个视图中循环是丑陋的。 You could use editor templates: 您可以使用编辑器模板:

@model IEnumerable<ViewModels.MyObject>
@using (Html.BeginForm())
{
    @Html.EditorForModel()
    <input type="submit" value="Go!" />
}

and inside the corresponding editor template which will be invoked for each item of the model collection ( ~/Views/Shared/EditorTemplates/MyObject.cshtml ): 在相应的编辑器模板中,将为模型集合的每个项目调用( ~/Views/Shared/EditorTemplates/MyObject.cshtml ):

@model ViewModels.MyObject
<div>
    @Html.LabelFor(x => x.Prop1)
    @Html.TextBoxFor(x => x.Prop1)
    @Html.ValidationMessageFor(x => x.Prop1)
</div>
<div>
    @Html.LabelFor(x => x.Prop2)
    @Html.TextBoxFor(x => x.Prop2)
    @Html.ValidationMessageFor(x => x.Prop2)
</div>
...

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

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