Michael Grassman
Michael Grassman

Reputation: 1935

Partials With View Data Object

I have the following ViewData that I pass into a view.

public class MerchantSignUpViewData : BaseViewData
{
    public Merchant Merchant { get; set; }
    public Address Address { get; set; }
    public Deal Deal { get; set; }
    public List<MerchantContact> Contacts { get; set; }
    public int TabIndex { get; set; }
    public List<DealPricing> DealPricing { get; set; }

}

I also created 3 partial views. Merchant Info, Address, Merchant Properties

In my View I have a Deal Model that shares the same field names as Merchant which is "Name"

I can't put these in the same form cause the names will be the same.

What I ended up doing was putting all 10 partial views into one huge form (I started crying at this point) and bound like this.

<%: Html.TextBoxFor(model => model.Deal.Name)%>
<%: Html.TextBoxFor(model => model.Deal.Name)%>

This gives me the correct names of the form elements.

What I want to do is the following.

<% Html.RenderPartial("MerchantForm", Model.Merchant) %>
<% Html.RenderPartial("DealForm", Model.Deal) %>

But how do I add a prefix to all the TextBoxFor pieces or preferable the render partial tags.

Hope I provided enough information or maybe I'm just doing this the wrong way. Either will help me in the long run so thanks in advance.

Upvotes: 0

Views: 220

Answers (1)

Chao
Chao

Reputation: 3043

Maybe I'm not quite getting the problem but I think this is exactly what Html.EditorFor(x=>x...) is for.

Create a folder called "EditorTemplates" in the same directory where your views are. Put your partials in here and give them the same name as your model type (eg rename "MerchantForm.ascx" to "Merchant.ascx").

In your main view instead of

Html.RenderPartial("MerchantForm", Model.Merchant)

use

Html.EditorFor(x=>x.Merchant)

The templating system will deal with the prefixes for you so that on post the model binder will tie everything up properly.

If you have templates set up for all the complex objects in the model you can even go a step further and on your main view just call

Html.EditorForModel()

Which will reflect over the properties in your model and call their relevant editors.

Upvotes: 1

Related Questions