Sam
Sam

Reputation: 1525

Multiple models in ASP view

I have an ASP/MVC view that displays data from a model and also contains a partial view with a form that uses a different model. Is there a way for me to combine these into one view? The result would be that the display values are based on model A but the form in the page submits model B. Is that possible?

Upvotes: 0

Views: 67

Answers (2)

Chris Pratt
Chris Pratt

Reputation: 239290

If the two things are closely related, you can use a view model to work with both in your view:

public class FooViewModel
{
    public SomeModelForDisplay Foo { get; set; }
    public SomeModelForForm Bar { get; set; }
}

In your action, initialize both:

public ActionResult Foo(int id)
{
    var foo = db.Foos.Find(id);
    if (foo == null)
    {
        return new HttpNotFoundResult();
    }

    var model = new FooViewModel
    {
        Foo = foo,
        Bar = new SomeModelForForm()
    };
    return View(model);
}

If the two things are not related at all, or in particular, if the partial is being called in something like your layout instead of the immediate view, then it's more appropriate to use a child action. Essentially, you'll just handle the display part as if nothing else was going on:

public ActionResult Foo(int id)
{
    var foo = db.Foos.Find(id);
    if (foo == null)
    {
        return new HttpNotFoundResult();
    }

    return View(foo);
}

Then, you'll add another action to handle the form:

[ChildActionOnly]
public ActionResult SomeForm()
{
    var model = new SomeModelForForm();
    return PartialView("_SomeForm", model);
}

Then, add a partial view to render just the form:

Views\Foo\_SomeForm.cshtml

@model SomeModelForForm

<!-- form fields here -->

Then, in your view/layout -- essentially wherever you want the form to actually be displayed:

@Html.Action("SomeForm", "Foo")

Where "Foo" here is the name of the controller this child action is in.

Upvotes: 1

clement
clement

Reputation: 4266

I recommand you to use model A that contains model B and C. B is loaded on the loading of the page and C is loaded with partial.

One other solution coule bethat you have a model A (given to razor page), then add model B to the page by using partial and then it return a mix of A and B. You just to make attention to the naming of the fields in order to make the model binding work properly, for instance

A has

  • firstName
  • lastName

and B has

  • street
  • phone

Then, if you put edirotfor both fields, model that can be received in controller could be model C that has

  • firstName
  • lastName
  • street
  • phone

Upvotes: 0

Related Questions