ASP.NET MVC LIST and Create in same view

2020-06-17 03:55发布

问题:

Ok I have a View thats is strongly typed as a collection of 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.

Is there a way to use Html helpers along wih lambda expressions to create elements strongly typed from my model?

or would it be best to load the Form portion of this page as another partial view typed as MyObject(not a collection)?

回答1:

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.

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.



回答2:

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):

@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>
...