I am new to MVC 4 and razor. I have a view which contains multiple partial views. Due to the functionality of the partial views I am planning to reuse these in other views also.
My model is a collection of complex objects e.g:
public class EmployeeInfo
{
public EmployeeContactInfo contactInfo { get; set; }
public List<TelephoneInfo> phoneDetails { get; set; }
public AddressDetails addressDetails { get; set; }
}
The model of my main view is EmployeeInfo
and other partial views have models as TelephoneInfo
, EmployeeContactInfo
and AddressDetails
respectively.
I tried using RenderPartial
, RenderAction
and Partial
to load my partial views e.g:
@using (Html.BeginForm())
{
@Html.Partial("ContactInfo",Model.contactInfo)
}
When the main form is submitted the main model doesnt have the updated values of the partial views.
I searched for this and found below 2 proposed solutions:
Use EditorFor
- It works and the model gets updated but I have collection of not only textbox but other controls which have some internal operations (like searching addresses) too and I also need to reuse the same partial view in other places (like a user control in classic ASP.NET)
Use RenderAction
instead of RenderPartial
- It didn't work for me.
Please let me know if I am going wrong or understood anything incorrectly.
A partial view is a Razor markup file ( . cshtml ) without an @page directive that renders HTML output within another markup file's rendered output. The term partial view is used when developing either an MVC app, where markup files are called views, or a Razor Pages app, where markup files are called pages.
Partial function which renders the Partial View. The name of the View and the object of the CustomerModel class are passed to the @Html. Partial function. In order to add Partial View, you will need to Right Click inside the Controller class and click on the Add View option in order to create a View for the Controller.
Another choice is to create an editor template. For example, in your main view:
@using (Html.BeginForm())
{
@(Html.EditorFor(m => m.ContactInfo))
}
Now, in your Views/Shared folder (or the Views/ControllerName folder eg Views/Home), create a new folder named "EditorTemplates". In that new folder create a cshtml view file named EmployeeContactInfo.cshtml
(tip, the name of the cshtml should be the data type name e.g. string
, bool
or in this case your customer contact info type). In that view file, put something like:
@model EmployeeContactInfo
@Html.LabelFor(m => m.Email)
@Html.TextBoxFor(m => m.Email)
When you post back to the controller, the values will be included as part of the returned model for you.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With