1

So im pretty much confused right now. I just finished to implement some functions into my website, where by my view got very big. I chose to clean up and separate the view, so i had 1 Main view, and multiple partial views which is loaded into Main. Oh boy what a surprise ive got on update/post response. After some research i found out that partial views simply does not bind to the model.

How do i actually separate my view in multiple files? is it possible to do without extra request to the server? Or MVC just suggests to have huge views?

2
  • Can you add the markup for your main view? Commented Feb 18, 2015 at 23:08
  • If your partials are based on a property in the model (e.g. a complex object) then the controls will not be correctly named unless you (a) pass the main model to the partial or (b) specify the HtmlFieldPrefix (refer this answer for an example). Alternatively you can use custom EditorTemplates for the typeof property. Commented Feb 18, 2015 at 23:17

1 Answer 1

3

Here's one (very simplified) way to do it. You need to use ViewModels.

public class PageViewModel
{
    public string Title { .. }
    public string Content { .. }
    public MyFormViewModel MyForm { .. }

}

public class MyFormViewModel
{
    public string Name { .. }
    public string Address { .. }
    // ... so on
}

Your Main Page View:

@model PageViewModel

<h1>@Model.Title</h1>
<p>@Model.Content</p>

<div class="my-form">
   @Html.Partial("_MyForm", Model.MyForm)
</div>

Your Form Partial ("_MyForm")

@model MyFormViewModel

@using(Html.BeginForm())
{
    <label>Name</label>
    @Html.TextBoxFor(m => m.Name)
}

Your Controller Actions:

// Load Page
[HttpGet]
public ActionResult MyPage()
{
    var viewModel = new PageViewModel();
    viewModel.MyForm = new MyFormViewModel();
    return View(viewModel);
}

// SubmitForm: Accepts MyFormViewModel
[HttpPost]
public ActionResult MyPage(MyFormViewModel viewModel)
{
   // do something with form data
}

On your main page view, you'll notice @Html.Partial(). This loads the partial with a model's property which in this case is MyForm. Due to this, your partial will have an @model of MyFormViewModel.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.