ModelState has errors when loading partial view using Html.Action - asp.net-mvc

I'm running into a problem with the ModelState already having errors when getting a PartialView using #Html.Action().
I have the following controller:
using System.ComponentModel.DataAnnotations;
using System.Linq;
using System.Web.Mvc;
public class TestController : Controller
{
private readonly object[] items = {new {Id = 1, Key = "Olives"}, new {Id = 2, Key = "Tomatoes"}};
[HttpGet]
public ActionResult Add()
{
var model = new ViewModel {List = new SelectList(items, "Id", "Key")};
return View(model);
}
public ActionResult _AddForm(ViewModel viewModel)
{
var errors = ModelState.Where(m => m.Value.Errors.Count > 0).ToArray();
return PartialView(viewModel);
}
}
And the following ViewModel:
public class ViewModel
{
[Required]
public int? SelectedValue { get; set; }
public SelectList List { get; set; }
}
The Add view looks like this:
#model ViewModel
<h1>Add a thing to a list</h1>
#using (Html.BeginForm())
{
#Html.ValidationSummary()
#Html.Action("_AddForm", Model)
<button class="btn btn-success">Submit</button>
}
Finally the _AddForm PartialView looks like this:
#model ViewModel
<div class="form-group">
#Html.ValidationMessageFor(m => m.SelectedValue)
#Html.LabelFor(m => m.SelectedValue, "Please select a thing:")
#Html.DropDownListFor(m => m.SelectedValue, Model.List, new {#class = "form-control"})
</div>
When this page loads the ModelState already has an error in the PartialView because the SelectedValue is required.
I don't understand why this happens, surely the _AddForm action is a HTTP GET and does not cause model state validation?
(Note, I don't want to use #Html.Partial() because I need to do some logic in the Action.)

The reason this occurs is that passing the strongly typed ViewModel as a parameter to the action causes the model binding and validation to occur again.
There seems to be no way to avoid this re-validation.
I originally attempted to use the Action as a way to get around the way MVC seemed to be caching some information about my ViewModel when using Html.Partial().
This "caching" turned out to be in the ModelState: https://stackoverflow.com/a/7449628/1775471

Related

pass multiple models data from controller to view MVC C# [duplicate]

I want to have 2 models in one view. The page contains both LoginViewModel and RegisterViewModel.
e.g.
public class LoginViewModel
{
public string Email { get; set; }
public string Password { get; set; }
}
public class RegisterViewModel
{
public string Name { get; set; }
public string Email { get; set; }
public string Password { get; set; }
}
Do I need to make another ViewModel which holds these 2 ViewModels?
public BigViewModel
{
public LoginViewModel LoginViewModel{get; set;}
public RegisterViewModel RegisterViewModel {get; set;}
}
I need the validation attributes to be brought forward to the view. This is why I need the ViewModels.
Isn't there another way such as (without the BigViewModel):
#model ViewModel.RegisterViewModel
#using (Html.BeginForm("Login", "Auth", FormMethod.Post))
{
#Html.TextBoxFor(model => model.Name)
#Html.TextBoxFor(model => model.Email)
#Html.PasswordFor(model => model.Password)
}
#model ViewModel.LoginViewModel
#using (Html.BeginForm("Login", "Auth", FormMethod.Post))
{
#Html.TextBoxFor(model => model.Email)
#Html.PasswordFor(model => model.Password)
}
There are lots of ways...
with your BigViewModel
you do:
#model BigViewModel
#using(Html.BeginForm()) {
#Html.EditorFor(o => o.LoginViewModel.Email)
...
}
you can create 2 additional views
Login.cshtml
#model ViewModel.LoginViewModel
#using (Html.BeginForm("Login", "Auth", FormMethod.Post))
{
#Html.TextBoxFor(model => model.Email)
#Html.PasswordFor(model => model.Password)
}
and register.cshtml same thing
after creation you have to render them in the main view and pass them the viewmodel/viewdata
so it could be like this:
#{Html.RenderPartial("login", ViewBag.Login);}
#{Html.RenderPartial("register", ViewBag.Register);}
or
#{Html.RenderPartial("login", Model.LoginViewModel)}
#{Html.RenderPartial("register", Model.RegisterViewModel)}
using ajax parts of your web-site become more independent
iframes, but probably this is not the case
I'd recommend using Html.RenderAction and PartialViewResults to accomplish this; it will allow you to display the same data, but each partial view would still have a single view model and removes the need for a BigViewModel
So your view contain something like the following:
#Html.RenderAction("Login")
#Html.RenderAction("Register")
Where Login & Register are both actions in your controller defined like the following:
public PartialViewResult Login( )
{
return PartialView( "Login", new LoginViewModel() );
}
public PartialViewResult Register( )
{
return PartialView( "Register", new RegisterViewModel() );
}
The Login & Register would then be user controls residing in either the current View folder, or in the Shared folder and would like something like this:
/Views/Shared/Login.cshtml: (or /Views/MyView/Login.cshtml)
#model LoginViewModel
#using (Html.BeginForm("Login", "Auth", FormMethod.Post))
{
#Html.TextBoxFor(model => model.Email)
#Html.PasswordFor(model => model.Password)
}
/Views/Shared/Register.cshtml: (or /Views/MyView/Register.cshtml)
#model ViewModel.RegisterViewModel
#using (Html.BeginForm("Login", "Auth", FormMethod.Post))
{
#Html.TextBoxFor(model => model.Name)
#Html.TextBoxFor(model => model.Email)
#Html.PasswordFor(model => model.Password)
}
And there you have a single controller action, view and view file for each action with each totally distinct and not reliant upon one another for anything.
Another way is to use:
#model Tuple<LoginViewModel,RegisterViewModel>
I have explained how to use this method both in the view and controller for another example: Two models in one view in ASP MVC 3
In your case you could implement it using the following code:
In the view:
#using YourProjectNamespace.Models;
#model Tuple<LoginViewModel,RegisterViewModel>
#using (Html.BeginForm("Login1", "Auth", FormMethod.Post))
{
#Html.TextBoxFor(tuple => tuple.Item2.Name, new {#Name="Name"})
#Html.TextBoxFor(tuple => tuple.Item2.Email, new {#Name="Email"})
#Html.PasswordFor(tuple => tuple.Item2.Password, new {#Name="Password"})
}
#using (Html.BeginForm("Login2", "Auth", FormMethod.Post))
{
#Html.TextBoxFor(tuple => tuple.Item1.Email, new {#Name="Email"})
#Html.PasswordFor(tuple => tuple.Item1.Password, new {#Name="Password"})
}
Note that I have manually changed the Name attributes for each property when building the form. This needs to be done, otherwise it wouldn't get properly mapped to the method's parameter of type model when values are sent to the associated method for processing. I would suggest using separate methods to process these forms separately, for this example I used Login1 and Login2 methods. Login1 method requires to have a parameter of type RegisterViewModel and Login2 requires a parameter of type LoginViewModel.
if an actionlink is required you can use:
#Html.ActionLink("Edit", "Edit", new { id=Model.Item1.Id })
in the controller's method for the view, a variable of type Tuple needs to be created and then passed to the view.
Example:
public ActionResult Details()
{
var tuple = new Tuple<LoginViewModel, RegisterViewModel>(new LoginViewModel(),new RegisterViewModel());
return View(tuple);
}
or you can fill the two instances of LoginViewModel and RegisterViewModel with values and then pass it to the view.
Use a view model that contains multiple view models:
namespace MyProject.Web.ViewModels
{
public class UserViewModel
{
public UserDto User { get; set; }
public ProductDto Product { get; set; }
public AddressDto Address { get; set; }
}
}
In your view:
#model MyProject.Web.ViewModels.UserViewModel
#Html.LabelFor(model => model.User.UserName)
#Html.LabelFor(model => model.Product.ProductName)
#Html.LabelFor(model => model.Address.StreetName)
Do I need to make another view which holds these 2 views?
Answer:No
Isn't there another way such as (without the BigViewModel):
Yes, you can use Tuple (brings magic in view having multiple model).
Code:
#model Tuple<LoginViewModel, RegisterViewModel>
#using (Html.BeginForm("Login", "Auth", FormMethod.Post))
{
#Html.TextBoxFor(tuple=> tuple.Item.Name)
#Html.TextBoxFor(tuple=> tuple.Item.Email)
#Html.PasswordFor(tuple=> tuple.Item.Password)
}
#using (Html.BeginForm("Login", "Auth", FormMethod.Post))
{
#Html.TextBoxFor(tuple=> tuple.Item1.Email)
#Html.PasswordFor(tuple=> tuple.Item1.Password)
}
Add this ModelCollection.cs to your Models
using System;
using System.Collections.Generic;
namespace ModelContainer
{
public class ModelCollection
{
private Dictionary<Type, object> models = new Dictionary<Type, object>();
public void AddModel<T>(T t)
{
models.Add(t.GetType(), t);
}
public T GetModel<T>()
{
return (T)models[typeof(T)];
}
}
}
Controller:
public class SampleController : Controller
{
public ActionResult Index()
{
var model1 = new Model1();
var model2 = new Model2();
var model3 = new Model3();
// Do something
var modelCollection = new ModelCollection();
modelCollection.AddModel(model1);
modelCollection.AddModel(model2);
modelCollection.AddModel(model3);
return View(modelCollection);
}
}
The View:
enter code here
#using Models
#model ModelCollection
#{
ViewBag.Title = "Model1: " + ((Model.GetModel<Model1>()).Name);
}
<h2>Model2: #((Model.GetModel<Model2>()).Number</h2>
#((Model.GetModel<Model3>()).SomeProperty
a simple way to do that
we can call all model first
#using project.Models
then send your model with viewbag
// for list
ViewBag.Name = db.YourModel.ToList();
// for one
ViewBag.Name = db.YourModel.Find(id);
and in view
// for list
List<YourModel> Name = (List<YourModel>)ViewBag.Name ;
//for one
YourModel Name = (YourModel)ViewBag.Name ;
then easily use this like Model
My advice is to make a big view model:
public BigViewModel
{
public LoginViewModel LoginViewModel{get; set;}
public RegisterViewModel RegisterViewModel {get; set;}
}
In your Index.cshtml, if for example you have 2 partials:
#addTagHelper *,Microsoft.AspNetCore.Mvc.TagHelpers
#model .BigViewModel
#await Html.PartialAsync("_LoginViewPartial", Model.LoginViewModel)
#await Html.PartialAsync("_RegisterViewPartial ", Model.RegisterViewModel )
and in controller:
model=new BigViewModel();
model.LoginViewModel=new LoginViewModel();
model.RegisterViewModel=new RegisterViewModel();
I want to say that my solution was like the answer provided on this stackoverflow page: ASP.NET MVC 4, multiple models in one view?
However, in my case, the linq query they used in their Controller did not work for me.
This is said query:
var viewModels =
(from e in db.Engineers
select new MyViewModel
{
Engineer = e,
Elements = e.Elements,
})
.ToList();
Consequently, "in your view just specify that you're using a collection of view models" did not work for me either.
However, a slight variation on that solution did work for me. Here is my solution in case this helps anyone.
Here is my view model in which I know I will have just one team but that team may have multiple boards (and I have a ViewModels folder within my Models folder btw, hence the namespace):
namespace TaskBoard.Models.ViewModels
{
public class TeamBoards
{
public Team Team { get; set; }
public List<Board> Boards { get; set; }
}
}
Now this is my controller. This is the most significant difference from the solution in the link referenced above. I build out the ViewModel to send to the view differently.
public ActionResult Details(int? id)
{
if (id == null)
{
return new HttpStatusCodeResult(HttpStatusCode.BadRequest);
}
TeamBoards teamBoards = new TeamBoards();
teamBoards.Boards = (from b in db.Boards
where b.TeamId == id
select b).ToList();
teamBoards.Team = (from t in db.Teams
where t.TeamId == id
select t).FirstOrDefault();
if (teamBoards == null)
{
return HttpNotFound();
}
return View(teamBoards);
}
Then in my view I do not specify it as a list. I just do "#model TaskBoard.Models.ViewModels.TeamBoards" Then I only need a for each when I iterate over the Team's boards. Here is my view:
#model TaskBoard.Models.ViewModels.TeamBoards
#{
ViewBag.Title = "Details";
}
<h2>Details</h2>
<div>
<h4>Team</h4>
<hr />
#Html.ActionLink("Create New Board", "Create", "Board", new { TeamId = #Model.Team.TeamId}, null)
<dl class="dl-horizontal">
<dt>
#Html.DisplayNameFor(model => Model.Team.Name)
</dt>
<dd>
#Html.DisplayFor(model => Model.Team.Name)
<ul>
#foreach(var board in Model.Boards)
{
<li>#Html.DisplayFor(model => board.BoardName)</li>
}
</ul>
</dd>
</dl>
</div>
<p>
#Html.ActionLink("Edit", "Edit", new { id = Model.Team.TeamId }) |
#Html.ActionLink("Back to List", "Index")
</p>
I am fairly new to ASP.NET MVC so it took me a little while to figure this out. So, I hope this post helps someone figure it out for their project in a shorter timeframe. :-)
Create one new class in your model and properties of LoginViewModel and RegisterViewModel:
public class UserDefinedModel()
{
property a1 as LoginViewModel
property a2 as RegisterViewModel
}
Then use UserDefinedModel in your view.
you can always pass the second object in a ViewBag or View Data.
This is a simplified example with IEnumerable.
I was using two models on the view: a form with search criteria (SearchParams model), and a grid for results, and I struggled with how to add the IEnumerable model and the other model on the same view. Here is what I came up with, hope this helps someone:
#using DelegatePortal.ViewModels;
#model SearchViewModel
#using (Html.BeginForm("Search", "Delegate", FormMethod.Post))
{
Employee First Name
#Html.EditorFor(model => model.SearchParams.FirstName,
new { htmlAttributes = new { #class = "form-control form-control-sm " } })
<input type="submit" id="getResults" value="SEARCH" class="btn btn-primary btn-lg btn-block" />
}
<br />
#(Html
.Grid(Model.Delegates)
.Build(columns =>
{
columns.Add(model => model.Id).Titled("Id").Css("collapse");
columns.Add(model => model.LastName).Titled("Last Name");
columns.Add(model => model.FirstName).Titled("First Name");
})
...
)
SearchViewModel.cs:
namespace DelegatePortal.ViewModels
{
public class SearchViewModel
{
public IEnumerable<DelegatePortal.Models.DelegateView> Delegates { get; set; }
public SearchParamsViewModel SearchParams { get; set; }
....
DelegateController.cs:
// GET: /Delegate/Search
public ActionResult Search(String firstName)
{
SearchViewModel model = new SearchViewModel();
model.Delegates = db.Set<DelegateView>();
return View(model);
}
// POST: /Delegate/Search
[HttpPost]
public ActionResult Search(SearchParamsViewModel searchParams)
{
String firstName = searchParams.FirstName;
SearchViewModel model = new SearchViewModel();
if (firstName != null)
model.Delegates = db.Set<DelegateView>().Where(x => x.FirstName == firstName);
return View(model);
}
SearchParamsViewModel.cs:
namespace DelegatePortal.ViewModels
{
public class SearchParamsViewModel
{
public string FirstName { get; set; }
}
}

ASP.NET MVC ModelState has error for IEnumeration<SelectListItem> in view model

In an ASP.NET MVC 5 web site, I am populating a drop down in a view and getting the value back in the POST action. However, ModelState.IsValid is always false. In investigating why, I found that there is an error for the IEnumerable<SelectListItem> property, which contains the data for the drop down.
Here is the exception from the ModelState for the IEnumerable<SelectListItem>property:
The parameter conversion from type 'System.String' to type 'System.Web.Mvc.SelectListItem' failed because no type converter can convert between these types.
From what I've read, it looks like I am using the view model correctly and setting up the drop down correctly.
Asp.net mvc ModelState validity when using dropdownlist
https://forums.asp.net/t/1715908.aspx
This is inconvenient because ModelState.IsValid is checked elsewhere for error handling, but in the POST action AvailableStates is irrelevant. Any ideas as to why the IEnumerable<SelectListItem> property always has this error?
I made a simple web site that replicates the issue.
View Model
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using System.Web.Mvc;
namespace SandboxAspNet.Models
{
public class HomeViewModel
{
[Required(ErrorMessage = "Please select a state.")]
[Display(Name = "State")]
public string SelectedState { get; set; }
public IEnumerable<SelectListItem> AvailableStates { get; set; }
}
}
Controller
using System.Collections.Generic;
using System.Web.Mvc;
using SandboxAspNet.Models;
namespace SandboxAspNet.Controllers
{
public class HomeController : Controller
{
[HttpGet]
public ActionResult Index()
{
var model = new HomeViewModel()
{
AvailableStates = GetAvailableStates()
};
return View(model);
}
[HttpPost]
public ActionResult Submit(HomeViewModel model)
{
if (!ModelState.IsValid)
{
model.AvailableStates = GetAvailableStates();
return View("Index", model);
}
return View("Success");
}
// Generate some dummy data for the drop down
private static IEnumerable<SelectListItem> GetAvailableStates()
{
return new List<SelectListItem>()
{
new SelectListItem()
{
Text = "Alabama",
Value = "AL"
},
new SelectListItem()
{
Text = "Alaska",
Value = "AK",
},
new SelectListItem()
{
Text = "Arizona",
Value = "AZ",
},
new SelectListItem()
{
Text = "Arkanasas",
Value = "AR"
}
};
}
}
}
View
#model SandboxAspNet.Models.HomeViewModel
#{
ViewBag.Title = "Home Page";
}
#using (Ajax.BeginForm("Submit", "Home", Model, null))
{
#Html.ValidationSummary()
<div>
<strong>#Html.LabelFor(model => model.SelectedState)</strong>
#Html.DropDownListFor(model => model.SelectedState, Model.AvailableStates, "--Select a State---", new { #type = "text", #style = "width:100%;", #class = "form-control" })
#Html.ValidationMessageFor(model => model.SelectedState)
</div>
<div>
<button type="submit">Submit</button>
</div>
}
Your third parameter to Ajax.BeginForm() is wrong. That parameter is for routeValues.
public static MvcForm BeginForm(
this AjaxHelper ajaxHelper,
string actionName,
string controllerName,
object routeValues,
AjaxOptions ajaxOptions
)
You can possibly just make the third and four parameter null if you don't need to do anything more advanced.
#using (Ajax.BeginForm("Submit", "Home", Model, null))

MVC5 ViewModel binding in HTTP GET?

I have an action like this
public ActionResult Overview(TimeAxisVM TimeAxis = null)
{
return View(new OverviewVM());
}
View model like this
public class TimeAxisVM
{
// omitted ctor
[DataType(DataType.DateTime)]
public DateTime? From { get; set; }
[DataType(DataType.DateTime)]
public DateTime? To { get; set; }
}
An editor template for the view model
#model TimeAxisVM
#using (Html.BeginForm("Overview", "Controller", FormMethod.Get))
{
#Html.EditorFor(model => model.From)
#Html.EditorFor(model => model.To)
<button type="submit">Submit</button>
}
And a view for the Overview action like this
#model OverviewVM
#Html.EditorFor(model => model.TimeAxis)
When I execute the GET request this is the query string is TimeAxis.From=22.+02.+2014&TimeAxis.To=25.+02.+2014 but once in the action TimeAxis.From and TimeAxis.To are both null.
If I change the form method to POST it immediately works as expected. From design point of view this should/has to be a GET request.
Any ideas how to make the model binding work for GET?
UPDATE:
Changing the action to
public ActionResult Overview(DateTime? From = null, DateTime? To = null)
and sending the request in this form: .../Overview/?From=22.+02.+2014&To=25.+02.+2014 works as well.
But I'd like to keep it encapsulated in the class and dont need to change the input field name - EditorFor generates them as TimeAxis.From and TimeAxis.To. I might add other properties to the ViewModel/form.
I found the answer. HTTP GET requests are culture invariant, whereas HTTP POST requests respect current culture in ASP.NET MVC.
http://weblogs.asp.net/melvynharbour/archive/2008/11/21/mvc-modelbinder-and-localization.aspx
If you want to bring the Model again into the view, you need to pass the ModelView back to the View like
return View(TimeAxis);
then, I think you do not have a controller called Controller do you? You might have a HomeController or something else, no?
in that case, please amend you form to
#using (Html.BeginForm("Overview", "Home", FormMethod.Get))
if for example you're Overview action is in the Home controller
all in all, your controller and view should be:
public ActionResult Overview(TimeAxisVM TimeAxis)
{
return View(TimeAxis);
}
and
#using (Html.BeginForm("Overview", "Home", FormMethod.Get))
{
#Html.EditorFor(Model => Model.From)
#Html.EditorFor(Model => Model.To)
<button type="submit">Submit</button>
}
here's the screencast of the code above: http://screencast.com/t/7G6ofEq0vZEo
Full source: http://ge.tt/1Uh80pK1/v/0?c

Tempdata In Razor

learning MVC creating a simple date time signup form. i am trying to make two textboxes for the user. One for date and one for time.
I am going to save both values in a single dateTime field in my model.
So i need to figure out how to have a form field stored in tempdata to be accessed in the controller when posted. i can then combine the two text boxes to make a dateTime to store in my model.
I know how to get the tempdata in the controller, its just the razor syntax in the form i cant quite get.
Thanks in advance.
TempData is not fit for your purpose. You can not assign value in TempData/ViewData in a View. You can assign value in TempData/ViewData in controller only and access those value in View. For more information please refer this question: TempData moving from view to controler
I suggest you to use a ViewModel in your scenario having all properties what you need in your view. Please look into answer given by Mariusz at ASP.NET MVC - How exactly to use View Models
I think a better practice would be to have a view model containing all the information you want to pass from the form to the controller.
View Model:
public class MyViewModel
{
public string Username { get; set; }
public string Password { get; set; }
public string Date { get; set; }
public string Time { get; set; }
}
Controller:
public ActionResult Signup()
{
var m = new MyViewModel();
return View(m);
}
[HttpPost]
public ActionResult Signup(MyViewModel m)
{
var username = m.Username;
var password = m.Password;
var date = m.Date;
var time = m.Time;
// ...
}
View:
#model MvcApplication5.Controllers.MyViewModel
#* ... *#
#using (Html.BeginForm())
{
#Html.TextBoxFor(m => m.Username)
#Html.PasswordFor(m => m.Password)
#Html.TextBoxFor(m => m.Date)
#Html.TextBoxFor(m => m.Time)
<input type="submit" value="Submit" />
}

Single strongly Typed Partial View for two similar classes of different types

I have a Register Primary View which shows two different types of Addresses 1. Home Address 2. Mailing Address
public class RegisterModel
{
public AddressModel HomeAddress { get; set; }
public AddressModel MailAddress { get; set; }
}
public class AddressModel
{
public string Street1 { get; set; }
public string Street2 { get; set; }
public string State { get; set; }
public string City { get; set; }
}
My main Register View is Strongly Typed to RegisterModel as follows
#model MyNamespace.Models.RegisterModel
#{
Layout = "~/Views/_Layout.cshtml";
}
#using (Html.BeginForm(null, null, FormMethod.Post, new { id = "myForm" }))
{
<div id="form">
#Html.Action("MyAddressPartial")
#Html.Action("MyAddressPartial")
</div>
}
MyAddressPartialView as follows : -
#model MyNamespace.Models.AddressModel
#{
Layout = "~/Views/_Layout.cshtml";
}
<div id="Address">
#Html.TextBoxFor(m=>m.Street1 ,new { #id="Street1 "})
#Html.TextBoxFor(m=>m.Street2,new { #id="Street2"})
#Html.TextBoxFor(m=>m.State ,new { #id="State "})
#Html.TextBoxFor(m=>m.City,new { #id="City"})
</div>
My RegisterController:-
// Have to instantiate the strongly Typed partial view when my form first loads
// and then pass it as parameter to "Register" post action method.
// As you can see the #Html.Action("MyAddressPartial") above in main
// Register View calls this.
public ActionResult MyAddressPartial()
{
return PartialView("MyAddressPartialView", new AddressModel());
}
I submit my Main Form to below mentioned action method in same Register Controller.
[HttpPost]
public ActionResult Register(RegisterModel model,
AddressModel homeAddress,
AddressModel mailingAddress)
{
//I want to access homeAddress and mailingAddress contents which should
//be different, but as if now it comes same.
}
I don't want to create a separate class one for MailingAddress and one for HomeAddress. if I do that then I will have to create two separate strongly typed partial views one for each address.
Any ideas on how to reuse the classes and partial views and make them dynamic and read their separate values in Action Method Post.
Edit 1 Reply to scott-pascoe:-
In DisplayTemplates Folder, I added following AddressModel.cshtml
<div>
#Html.DisplayFor(m => m.Street1);
#Html.DisplayFor(m => m.Street2);
#Html.DisplayFor(m => m.State);
#Html.DisplayFor(m => m.City);
</div>
Also In EditorTemplate Folder, I added following AddressModel.cshtml but with EditorFor
<div>
#Html.EditorFor(m => m.Street1);
#Html.EditorFor(m => m.Street2);
#Html.EditorFor(m => m.State);
#Html.EditorFor(m => m.City);
</div>
Now how do i use them in RegisterView and also how i read values in Controller's post Action Method ? What else would have to be modified ? I have added almost entire code above. I am pretty beginner to MVC.
The typical ASP.NET MVC method for doing this is to use EditorTemplates and DisplayTemplates for your custom types.
In ~/Views/Shared, Create two folders, DisplayTemplates, and EditorTemplates.
In the DisplayTemplates folder create a partial view with the name of your Model, ie (AddressModel), and create a DisplayFor Template.
In the EditorTemplates folder create another partial view named AddressModel.cshtml and create an EditorFor Template.
MVC will then automatically use your templates and give you the data that you are asking for.
Use #Html.EditorFor (or #Html.DisplayFor, for display) in your view:
#model MyNamespace.Models.RegisterModel
#{
Layout = "~/Views/_Layout.cshtml";
}
#using (Html.BeginForm(null, null, FormMethod.Post, new { id = "myForm" }))
{
<div id="form">
#Html.EditorFor(m => m.HomeAddress)
#Html.EditorFor(m => MailAddress)
</div>
}
You will not need to have a separate controller action for the parts, just populate the addresses in the RegisterModel before in your controller. Like this:
[HttpGet]
public ActionResult Register() // this will be the page people see first
{
var model = new RegisterModel();
return View(model); // assuming your view is called Register.cshtml
}
[HttpPost]
public ActionResult Register(RegisterModel model){
DosomethingWithHomeAddress(model.HomeAddress);
DosomethingWithMailAddress(model.MailAddress);
model.IsSaved = true; // some way to let the user knwo that save was successful;
// if this is true, display a paragraph on the view
return View(model);
}

Resources