Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

ASP.NET MVC LIST and Create in same view

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

like image 765
stephen776 Avatar asked Feb 22 '11 22:02

stephen776


2 Answers

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.

like image 134
LukLed Avatar answered Oct 05 '22 19:10

LukLed


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>
...
like image 20
Darin Dimitrov Avatar answered Oct 05 '22 20:10

Darin Dimitrov