Object is not passed from view to controller when ViewModel is used

Multi tool use
Object is not passed from view to controller when ViewModel is used
*
Hey Guys need your help with data not being passed to controller. I encountered with emplty data passed from view to controller. So, whenever I use the viewmodel in the parameter of action method the posted object is properly passed but when I use customer model which inside the viewmodel then the data that I try to submit to database is not passed. Here is the view code:
*
@model WebApplication2.Models.CustomerViewModel
@{
ViewBag.Title = "CreateForm";
Layout = "~/Views/Shared/_Layout.cshtml";
}
<h2>CreateForm</h2>
@using(Html.BeginForm("Create", "Customer"))
{
@Html.LabelFor(m=>m.Customers.Name)
@Html.TextBoxFor(m=>m.Customers.Name, new { @class="form-control"})
@Html.LabelFor(m => m.Customers.Birthdate)
@Html.TextBoxFor(m => m.Customers.Birthdate, new { @class = "form-control" })
@Html.LabelFor(m => m.Customers.MembershipTypeId)
@Html.DropDownListFor(m => m.Customers.MembershipTypeId, new SelectList(Model.MembershipTypes, "Id", "Name"),"Select", new { @class = "form-control" })
<button type"submit" class="btn btn-primary">Save</button>
}
Controller code
[HttpPost]
public ActionResult Create(Customer customer)//data is not passed when I use Customer but is passed when CustomerViewModel is used
{
context.Customer.Add(customer);
context.SaveChanges();
return RedirectToAction("Index", "Customer");
}
1 Answer
1
look at the first line of your view, its:-
@model WebApplication2.Models.CustomerViewModel
so your view is a strongly typed view and its model is defined as CustomerViewModel, change model to Customer if you want Customer to be posted to your action method
By clicking "Post Your Answer", you acknowledge that you have read our updated terms of service, privacy policy and cookie policy, and that your continued use of the website is subject to these policies.
Hi Fakhar thank you for your attention and reply:) Yes you are right I have to put Customer instead of CustomerViewModel but CustomerViewModel holds two models as Customer and IEnumarable of MembershipType the code: public class CustomerViewModel { public IEnumerable<MembershipType> MembershipTypes { get; set; } public Customer Customers { get; set; } }.So I need these models in the view IEnumerable is needed for dropdownlist and Customer for the other properties thus Customer in the view is not possible
– Mir Usmanov
1 hour ago