I've been around this for a couple of time and I would love if possible for a couple of "fresh" pair of eyes to look at this.
In my app I have a form where I use a model with some primitive types and two lists. Also I'm using a Kendo grid.
My problem is that when the user does Submit, the model arrives ok but one of the two lists returns with 0 elements...! (never null)
The list that arrives ok is the one I'm creating in the Kendo Grid.
The list that returns empty is List ProductItemlist, that is generated in the partial view (also tried not using the partial view).
The thing is, on the controller if I do:
string test = Request.Form["ProductItemlist[0].ProductItemId"],
I get the values I want, so the problem I think must be in the mapping.
Nevertheless I'm failing in discovering it....
What's happenning...? Thanks in advance for any help!
My Model:
public class PurchaseRegistrationProductEditVM
{
public int ClientId { get; set; }
public int ProductId { get; set; }
public int EnterpriseId { get; set; }
public int HeadquarterId { get; set; }
public string Name { get; set; }
public DateTime StartDate { get; set; }
public DateTime? EndDate { get; set; }
public int StatusId { get; set; }
public int? RUC { get; set; }
public string RUCName { get; set; }
public string RUCAddress { get; set; }
public List<PurchaseRegistrationProductItemEditVM> ProductItemlist { get; set; }
public List<ClientProductPurchaseRegistryComissionEditVM> ComissionList { get; set; }
}
Model PurchaseRegistrationProductItemEditVM:
public class PurchaseRegistrationProductItemEditVM{
public int ProductItemId { get; set; }
public string ProductItemName { get; set; }
public int ProductItemTypeId { get; set; }
public string ProductItemTypeName { get; set; }
public DateTime? StartCourseDate { get; set; }
public DateTime? EndCourseDate { get; set; }
public decimal Amount { get; set; }
public int ExpiryDays { get; set; }
public string Size { get; set; }
public int DiscountTypeId { get; set; }
public string DiscountTypeName { get; set; }
public decimal? Discount { get; set; }
public int? MonthlyPaymentDueDay { get; set; }
public decimal? MonthlyPaymentDuePenalty { get; set; }
public DateTime MatriculationStartDate { get; set; }
public string MatriculationObservation { get; set; }
}
Model: ClientProductPurchaseRegistryComissionEditVM
public class ClientProductPurchaseRegistryComissionEditVM
{
public int Id { get; set; }
public int ClientProductPurchaseRegistryId { get; set; }
public string EmployeeName { get; set; }
public int EmployeeId { get; set; }
public string Observations { get; set; }
}
My View:
#model PurchaseRegistrationProductEditVM
#{
Layout = "~/Areas/Backoffice/Views/Shared/_Layout.cshtml";
}
#using (Html.BeginForm("ProcessPurchases", "Client"))
{
#Html.AntiForgeryToken()
#Html.ValidationSummary(true)
#Html.HiddenFor(model => model.ClientId)
#Html.HiddenFor(model => model.EndDate)
#Html.HiddenFor(model => model.EnterpriseId)
#Html.HiddenFor(model => model.HeadquarterId)
#Html.HiddenFor(model => model.Name)
#Html.HiddenFor(model => model.ProductId)
#Html.HiddenFor(model => model.ProductItemlist)
#Html.HiddenFor(model => model.StartDate)
#Html.HiddenFor(model => model.StatusId)
#Html.Partial("_PartialViewProductItem")
<div class="form_sep">
#Html.Label(Resources.Client_Pending_Payment_Label_Comission)
#(Html.Kendo().ComboBox()
.Name("EmployeeComissionComboBox")
.Placeholder(Resources.Employee_ComboBox)
.DataTextField("Text")
.DataValueField("Value")
.Filter(FilterType.Contains)
.DataSource(source =>
{
source.Read(read =>
{
read.Action("GetEmployeesComboBox", "Client", new { EnterpriseId = #Model.EnterpriseId });
})
.ServerFiltering(true);
})
)
</div>
<div class="form_sep">
#Html.Label(Resources.Client_Purchase_Registry_Comission_Field_Observations)
#Html.TextBox("PurchaseComissionObservations", "", new { maxlength = 50, size = 10, #class = "form-control" })
</div>
<div class="form_sep">
#(Html.Kendo().Button()
.Name("EmployeeComissionAddButton")
.HtmlAttributes(new { type = "button", #class = "k-primary" })
.Content(Resources.Client_SelectedPayments_Button_Add_Employee_Comission)
.Events(ev => ev.Click("onClickAddEmployeeComission"))
)
</div>
<div class="form_sep">
#Html.Label(Resources.Client_Purchase_Registry_Grid_Added_Employees)
#(Html.Kendo().Grid<ClientProductPurchaseRegistryComissionEditVM>()
.Name("PurchaseCommissionGrid")
.HtmlAttributes(new { style = "height:150px;" })
.Columns(columns =>
{
columns.Bound(o => o.EmployeeName).Filterable(f => f.Cell(c => c.ShowOperators(false))).ClientTemplate("#= EmployeeName #<input type='hidden' name='ComissionList[#= indexPurchaseComissionGrid(data)#].EmployeeName' value='#= EmployeeName #' />");
columns.Bound(o => o.EmployeeId).Hidden().Filterable(f => f.Cell(c => c.ShowOperators(false))).ClientTemplate("#= EmployeeId #<input type='hidden' name='ComissionList[#= indexPurchaseComissionGrid(data)#].EmployeeId' value='#= EmployeeId #' />");
columns.Bound(o => o.Observations).Filterable(f => f.Cell(c => c.ShowOperators(false))).ClientTemplate("#= Observations #<input type='hidden' name='ComissionList[#= indexPurchaseComissionGrid(data)#].Observations' value='#= Observations #' />");
columns.Command(command =>
{
command.Custom("Remove").Text(Resources.Site_Link_Remove).Click("onDeleteEmployeeComission");
});
})
.DataSource(dataSource => dataSource
.Ajax()
.PageSize(5)
)
.Pageable()
.Sortable()
.Scrollable())
</div>
<div class="form_sep">
#Html.LabelFor(model => model.RUC)
#Html.TextBoxFor(model => model.RUC, new { #class = "form-control" })
#Html.ValidationMessageFor(model => model.RUC)
</div>
<div class="form_sep">
#Html.LabelFor(model => model.RUCName)
#Html.TextBoxFor(model => model.RUCName, new { #class = "form-control" })
#Html.ValidationMessageFor(model => model.RUCName)
</div>
<div class="form_sep">
#Html.LabelFor(model => model.RUCAddress)
#Html.TextBoxFor(model => model.RUCAddress, new { #class = "form-control" })
#Html.ValidationMessageFor(model => model.RUCAddress)
<input id="btnSubmit" type="submit" value="#Resources.FO_Client_Link_Buy_Product" class="btn btn-default" />
#Html.ActionLink(Resources.Site_Link_Back, "PurchaseProduct/" + #Model.ClientId, "Client", new { Area = "Frontoffice" }, new { #class = "btn btn-default" })
}
Partial View:
#model PurchaseRegistrationProductEditVM
#for (int i = 0; i < Model.ProductItemlist.Count; i++)
{
#Html.HiddenFor(model => model.ProductItemlist[i].Amount)
#Html.HiddenFor(model => model.ProductItemlist[i].Discount)
#Html.HiddenFor(model => model.ProductItemlist[i].DiscountTypeId)
#Html.HiddenFor(model => model.ProductItemlist[i].DiscountTypeName)
#Html.HiddenFor(model => model.ProductItemlist[i].EndCourseDate)
#Html.HiddenFor(model => model.ProductItemlist[i].ExpiryDays)
#Html.HiddenFor(model => model.ProductItemlist[i].MonthlyPaymentDueDay)
#Html.HiddenFor(model => model.ProductItemlist[i].MonthlyPaymentDuePenalty)
#Html.HiddenFor(model => model.ProductItemlist[i].ProductItemId)
#Html.HiddenFor(model => model.ProductItemlist[i].ProductItemName)
#Html.HiddenFor(model => model.ProductItemlist[i].ProductItemTypeId)
#Html.HiddenFor(model => model.ProductItemlist[i].ProductItemTypeName)
#Html.HiddenFor(model => model.ProductItemlist[i].Size)
#Html.HiddenFor(model => model.ProductItemlist[i].StartCourseDate)
if (Model.ProductItemlist[i].ProductItemTypeId == 1)
{
DateTime date = DateTime.Now;
if (date < Model.ProductItemlist[i].StartCourseDate.Value)
{
date = Model.ProductItemlist[i].StartCourseDate.Value;
}
//Case Course
<div class="form_sep">
<b>#Resources.Site_Link_Course #Html.LabelFor(model => model.ProductItemlist[i].ProductItemName)</b>
</div>
<div class="form_sep">
#Html.LabelFor(model => model.ProductItemlist[i].MatriculationStartDate)
#(Html.Kendo().DatePickerFor(model => model.ProductItemlist[i].MatriculationStartDate)
.Animation(true)
.Culture("pt-PT")
.Format("dd-MM-yyyy")
.Value(date)
.Min(Model.ProductItemlist[i].StartCourseDate.Value)
.Max(Model.ProductItemlist[i].EndCourseDate.Value)
)
#Html.ValidationMessageFor(model => model.ProductItemlist[i].MatriculationStartDate)
</div>
//Observations
<div class="form_sep">
#Html.LabelFor(model => model.ProductItemlist[i].MatriculationObservation)
#Html.TextBoxFor(model => model.ProductItemlist[i].MatriculationObservation, new { #class = "form-control" })
#Html.ValidationMessageFor(model => model.ProductItemlist[i].MatriculationObservation)
</div>
}
}
My Controller:
[HttpPost]
public ActionResult ProcessPurchases(PurchaseRegistrationProductEditVM model)
{
Log.Instance.Info(string.Format(LogConst.CONTROLLER, "Client", "ProcessPayments", "Get"));
string test = Request.Form["ProductItemlist[0].ProductItemId"];
return RedirectToAction("Details/" + model.ClientId, "Client");
}
After a good night sleep I was able to solve this issue! :)
In the end the problem was this line:
#Html.HiddenFor(model => model.ProductItemlist)
Since I was already storing a list of the same type the form mapper used the first he got. And since you can't save entire lists in hidden fields... it returned a list initialized with 0 elements!
After deleting the line everything started working like a charm!
Related
I send data from view to action. Chrome browser shows that Genre_Id is sent properly as it you see the attached screenshot but when it is received by the action, Visual Studio raises exception and shows it as Null / 0 as you see the attached screenshot. So why does this happen?
this is Movie Model
public class Movie
{
public int Id { get; set; }
[Required]
[StringLength(255)]
public string Name { get; set; }
[Required]
[Display(Name="Created on")]
public DateTime DateAdded { get; set; }
[Required]
[Display(Name = "Release Date")]
public DateTime ReleaseDate { get; set; }
[Required]
[Display(Name = "Number in Stock")]
public int NumberInStock { get; set; }
public Genre Genre { get; set; }
[Display(Name="Genre")]
public int Genre_Id;
}
this is the Form
#using(Html.BeginForm("Save", "Movies"))
{
<div class="form-group">
#Html.LabelFor(m => m.Movie.Name)
#Html.TextBoxFor(m => m.Movie.Name, new { #class="form-control"})
</div>
<div class="form-group">
#Html.LabelFor(m => m.Movie.DateAdded)
#Html.TextBoxFor(m => m.Movie.DateAdded, new { #class="form-control"})
</div>
<div class="form-group">
#Html.LabelFor(m => m.Movie.ReleaseDate)
#Html.TextBoxFor(m => m.Movie.ReleaseDate, new { #class="form-control"})
</div>
<div class="form-group">
#Html.LabelFor(m => m.Movie.NumberInStock)
#Html.TextBoxFor(m => m.Movie.NumberInStock, new { #class="form-control" })
</div>
<div class="form-group">
#Html.LabelFor(m => m.Movie.Genre_Id)
#Html.TextBoxFor(m => m.Movie.Genre_Id, new { #class="form-control"})
</div>
#Html.HiddenFor(m => m.Movie.Id)
<button type="submit" class="btn btn-primary">Save</button>
}
Look at the icons, the Genre_Id member looks different. That's because it's a field, not a property.
MVC requires model members to be properties. Add { get; set; } to its declaration.
I'm having trouble retrieving the correct value to my DropDownList Control within the Edit Action.
Customer Model:
public class Customer
{
public int CustId { get; set; }
public string CustDisplayName { get; set; }
public string CustFirstName { get; set; }
public string CustLastName { get; set; }
public string CustCompanyName { get; set; }
public string CustAddress { get; set; }
public string CustPhoneNumber { get; set; }
public string CustMobileNumber { get; set; }
public string CustEmailAddress { get; set; }
public int StId { get; set; }
public State State { get; set; }
}
State Model:
public class State
{
public int StId { get; set; }
public string StAbbr { get; set; }
public List<Customer> Customers { get; set; }
}
Manufacturer Model:
public class Manufacturer
{
public int MfrId { get; set; }
public string MfrCompanyName { get; set; }
public string MfrWebsiteDomainName { get; set; }
}
CustomerFormViewModel
public class CustomerFormViewModel
{
public int CustId { get; set; }
[Required(ErrorMessage = "Display Name is required!")]
[Display(Name = "Display Name")]
[StringLength(100)]
public string CustDisplayName { get; set; }
[Display(Name = "First Name")]
[StringLength(50)]
public string CustFirstName { get; set; }
[Display(Name = "Last Name")]
[StringLength(50)]
public string CustLastName { get; set; }
[Display(Name = "Company Name")]
[StringLength(50)]
public string CustCompanyName { get; set; }
[Display(Name = "Phone Number")]
[DataType(DataType.PhoneNumber)]
[StringLength(12)]
[RegularExpression(#"((\(\d{3}\) ?)|(\d{3}-))?\d{3}-\d{4}", ErrorMessage = "Invalid Phone Number format!")]
public string CustPhoneNumber { get; set; }
[Display(Name = "Mobile Number")]
[DataType(DataType.PhoneNumber)]
[StringLength(12)]
[RegularExpression(#"((\(\d{3}\) ?)|(\d{3}-))?\d{3}-\d{4}", ErrorMessage = "Invalid Number!")]
public string CustMobileNumber { get; set; }
[Display(Name = "Email Address")]
[DataType(DataType.EmailAddress)]
[StringLength(320)]
public string CustEmailAddress { get; set; }
[Required(ErrorMessage = "Address is required!")]
[Display(Name = "Address")]
[StringLength(100)]
public string CustAddress { get; set; }
[Required(ErrorMessage = "State is required!")]
[Display(Name = "State")]
public int StId { get; set; }
public IEnumerable<State> States { get; set; }
}
CustomerController:
public class CustomerController : Controller
{
private WebAppDbContext _context;
public CustomerController(WebAppDbContext context)
{
_context = context;
}
// GET: /<Customer>/
public IActionResult Index()
{
return View(_context.Customers.ToList());
}
public ActionResult Create()
{
var states = _context.States.ToList();
var viewModel = new CustomerFormViewModel
{
States = states
};
return View(viewModel);
}
[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult Create(CustomerFormViewModel vm)
{
if (ModelState.IsValid)
{
var customer = new Customer();
{
customer.CustDisplayName = vm.CustDisplayName;
customer.CustFirstName = vm.CustFirstName;
customer.CustLastName = vm.CustLastName;
customer.CustCompanyName = vm.CustCompanyName;
customer.CustAddress = vm.CustAddress;
customer.CustPhoneNumber = vm.CustPhoneNumber;
customer.CustMobileNumber = vm.CustMobileNumber;
customer.CustEmailAddress = vm.CustEmailAddress;
customer.StId = vm.StId;
}
_context.Customers.Add(customer);
_context.SaveChanges();
return RedirectToAction("Index");
}
else
{
vm.States = _context.States.ToList();
return View(vm);
}
}
public ActionResult Edit(int? id)
{
if (id == null)
{
return NotFound();
}
var customervm = new CustomerFormViewModel();
{
Customer customer = _context.Customers.SingleOrDefault(c => c.CustId == id);
if (customer == null)
{
return NotFound();
}
customervm.CustId = customer.CustId;
customervm.CustDisplayName = customer.CustDisplayName;
customervm.CustFirstName = customer.CustFirstName;
customervm.CustLastName = customer.CustLastName;
customervm.CustCompanyName = customer.CustCompanyName;
customervm.CustAddress = customer.CustAddress;
customervm.CustPhoneNumber = customer.CustPhoneNumber;
customervm.CustMobileNumber = customer.CustMobileNumber;
customervm.CustEmailAddress = customer.CustEmailAddress;
customervm.StId = customer.StId;
}
return View(customervm);
}
}
Create View:
<div class="form-group">
#Html.LabelFor(c => c.CustDisplayName)
#Html.TextBoxFor(c => c.CustDisplayName, new { #class = "form-control" })
#Html.ValidationMessageFor(c => c.CustDisplayName)
</div>
<div class="form-group">
#Html.LabelFor(c => c.CustFirstName)
#Html.TextBoxFor(c => c.CustFirstName, new { #class = "form-control" })
</div>
<div class="form-group">
#Html.LabelFor(c => c.CustLastName)
#Html.TextBoxFor(c => c.CustLastName, new { #class = "form-control" })
</div>
<div class="form-group">
#Html.LabelFor(c => c.CustCompanyName)
#Html.TextBoxFor(c => c.CustCompanyName, new { #class = "form-control" })
</div>
<div class="form-group">
#Html.LabelFor(c => c.CustAddress)
#Html.TextBoxFor(c => c.CustAddress, new { #class = "form-control" })
#Html.ValidationMessageFor(c => c.CustAddress)
</div>
<div class="form-group">
#Html.LabelFor(c => c.CustPhoneNumber)
#Html.TextBoxFor(c => c.CustPhoneNumber, new { #class = "form-control" })
#Html.ValidationMessageFor(c => c.CustPhoneNumber)
</div>
<div class="form-group">
#Html.LabelFor(c => c.CustMobileNumber)
#Html.TextBoxFor(c => c.CustMobileNumber, new { #class = "form-control" })
#Html.ValidationMessageFor(c => c.CustMobileNumber)
</div>
<div class="form-group">
#Html.LabelFor(c => c.CustEmailAddress)
#Html.TextBoxFor(c => c.CustEmailAddress, new { #class = "form-control" })
#Html.ValidationMessageFor(c => c.CustEmailAddress)
</div>
<div class="form-group">
#Html.LabelFor(s => s.StId)
#Html.DropDownListFor(s => s.StId, new SelectList(Model.States, "StId", "StAbbr"), "", new { #class = "form-control" })
#Html.ValidationMessageFor(s => s.StId)
</div>
<div class="form-group">
<button type="submit" class="btn btn-primary">Submit</button>
</div>
Edit View:
<div class="form-group">
#Html.LabelFor(c => c.CustDisplayName)
#Html.TextBoxFor(c => c.CustDisplayName, new { #class = "form-control" })
#Html.ValidationMessageFor(c => c.CustDisplayName)
</div>
<div class="form-group">
#Html.LabelFor(c => c.CustFirstName)
#Html.TextBoxFor(c => c.CustFirstName, new { #class = "form-control" })
</div>
<div class="form-group">
#Html.LabelFor(c => c.CustLastName)
#Html.TextBoxFor(c => c.CustLastName, new { #class = "form-control" })
</div>
<div class="form-group">
#Html.LabelFor(c => c.CustCompanyName)
#Html.TextBoxFor(c => c.CustCompanyName, new { #class = "form-control" })
</div>
<div class="form-group">
#Html.LabelFor(c => c.CustAddress)
#Html.TextBoxFor(c => c.CustAddress, new { #class = "form-control" })
#Html.ValidationMessageFor(c => c.CustAddress)
</div>
<div class="form-group">
#Html.LabelFor(c => c.CustPhoneNumber)
#Html.TextBoxFor(c => c.CustPhoneNumber, new { #class = "form-control" })
#Html.ValidationMessageFor(c => c.CustPhoneNumber)
</div>
<div class="form-group">
#Html.LabelFor(c => c.CustMobileNumber)
#Html.TextBoxFor(c => c.CustMobileNumber, new { #class = "form-control" })
#Html.ValidationMessageFor(c => c.CustMobileNumber)
</div>
<div class="form-group">
#Html.LabelFor(c => c.CustEmailAddress)
#Html.TextBoxFor(c => c.CustEmailAddress, new { #class = "form-control" })
#Html.ValidationMessageFor(c => c.CustEmailAddress)
</div>
<div class="form-group">
#Html.LabelFor(s => s.StId)
#Html.DropDownListFor(s => s.StId, new SelectList(Model.States, "StId", "StAbbr"), "", new { #class = "form-control" })
#Html.ValidationMessageFor(s => s.StId)
</div>
#Html.HiddenFor(c => c.CustId)
<div class="form-group">
<button type="submit" class="btn btn-primary">Update</button>
</div>
It is same as your create action, Load the collection property for all states (States) and also set the property for the selected item (StId) on your view model object.
So add this code to your Edit GET action method.
var customervm = new CustomerFormViewModel();
{
// Your existing code to map the entity property values goes here
}
//Load all the states
var states = _context.States.ToList();
customervm.States = states;
//Set the selected state
customervm.StId = customer.StId;
return View();
I have a little blog application with posts and tags. This is my model for Post:
namespace HelloWorld.Models
{
public class Post
{
[Required]
[DataType(DataType.Text)]
public string Title { get; set; }
[Required]
[DataType(DataType.MultilineText)]
public string Description { get; set; }
[Required]
[DataType(DataType.DateTime)]
public DateTime PostDate { get; set; }
public List<Tag> Tags { get; set; }
[Required]
public int PostId { get; set; }
}
public class CreatePostView
{
[Required]
[DataType(DataType.Text)]
public string Title { get; set; }
[Required]
[DataType(DataType.MultilineText)]
public string Description { get; set; }
[Display(Name = "Tags")]
[Required(ErrorMessage = "Please select a tag")]
public string SelectedTag { get; set; }
public SelectList TagList { get; set; }
[Required]
public int PostId { get; set; }
}
}
And model of Tag consist of string TagName, int TagId, List Posts.
When I create a new Post I use CreatePostView and my view is:
#using (Html.BeginForm())
{
#Html.AntiForgeryToken()
<div class="create-post-form">
#Html.ValidationSummary(true, "", new { #class = "text-danger" })
<div class="form-group">
<strong>Title</strong>
<div class="col-md-10">
#Html.EditorFor(model => model.Title, new { htmlAttributes = new { #class = "form-control" } })
#Html.ValidationMessageFor(model => model.Title, "", new { #class = "text-danger" })
</div>
</div>
<div class="form-group">
<strong>Description</strong>
<div class="col-md-10">
#Html.EditorFor(model => model.Description, new { htmlAttributes = new { #class = "form-control" } })
#Html.ValidationMessageFor(model => model.Description, "", new { #class = "text-danger" })
</div>
</div>
#Html.DropDownListFor(m => m.SelectedTag, Model.TagList, "Add tag")
#Html.ValidationMessageFor(m => m.SelectedTag)
<div class="post-create-button">
<input type="submit" value="Create">
</div>
<div class="back-to-list-button">
#Html.ActionLink("Back", "Index")
</div>
</div>
}
And now I want to display my tag that I selected. I put value of selected tag in ViewBag, but it does not display. Maybe it's silly, but I do not know how to fix it. My Create action of PostsController:
// POST: Posts/Create
[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult Create(CreatePostView post)
{
Post currPost = new Post {
Title = post.Title,
Description = post.Description,
PostDate = DateTime.Now,
Tags = null };
ViewBag.Tag = post.SelectedTag.ToString();
ViewBag.Trash = "texttexttexttexttext"; // It's strange, but it not displayed.
if (ModelState.IsValid)
{
//var tags = db.Tags.Where(s => s.TagName.Equals(post.SelectedTag)).ToList();
//currPost.Tags = tags;
db.Posts.Add(currPost);
db.SaveChanges();
return RedirectToAction("Index", "Posts");
}
return View(currPost);
}
My view with all Posts (use model Post)
#foreach (var item in Model)
{
<article class="post">
<h3>#Html.DisplayFor(modelItem => item.Title)</h3>
<p>#Html.DisplayFor(modelItem => item.Description)</p>
<!--None of them is not shown-->
<p><strong>Tag: #ViewBag.Tag</strong></p>
<p><strong>Trash: #ViewBag.Trash</strong></p>
</article>
}
ViewBag is used when returning a view, not when redirecting to another action. Basically it doesn't persist across separate requests. Try using TempData instead:
TempData["Tag"] = post.SelectedTag.ToString();
and in the view:
<p><strong>Tag: #TempData["Tag"]</strong></p>
I wonder why i get null model passing from the view to the controller.
Here is my code in the view (UpdatePersonal.cshtml):
#model Project.Models.UserInfo
#using (Html.BeginForm()){
#Html.LabelFor(m => m.userinfo.firstname);
#Html.TextBoxFor(m => m.userinfo.firstname, new { #Value = ViewBag.Firstname });
#Html.LabelFor(m => m.userinfo.lastname);
#Html.TextBoxFor(m => m.userinfo.lastname, new { #Value = ViewBag.Lastname });
#Html.LabelFor(m => m.userinfo.email);
#Html.TextBoxFor(m => m.userinfo.email, new { #Value = ViewBag.Email });
#Html.LabelFor(m => m.userinfo.phone);
#Html.TextBoxFor(m => m.userinfo.phone, new { #Value = ViewBag.Phone });
#Html.HiddenFor(m => m.username, new { #Value = ViewBag.Username });
<input type="submit" value="Submit" />}
Here is the action method that accepts it:
[HttpPost]
[AllowAnonymous]
public ActionResult UpdatePersonal(UserInfo userInfo){
//some code here
//my breakpoint}
i see the model being passed has null value as i used breakpoint
my model:
public class UserInfo
{
[BsonId]
public string username { get; set; }
public Info userinfo { get; set; }
public Address address { get; set; }
public class Info
{
public string firstname { get; set; }
public string lastname { get; set; }
public string email { get; set; }
public string phone { get; set; }
}
public class Address
{
public string street { get; set; }
public string address1 { get; set; }
public string address2 { get; set; }
public string postalcode { get; set; }
public string country { get; set; }
}
}
You work around the problem but your first code was good, the only problem was the name of your action method param was the same that the name of your model property.
Change your action method signature for example by :
public ActionResult UpdatePersonal(UserInfo info)
and it should be work !
I just solved my problem, instead i used and pass the subclass
#model Buch_Ankauf.Models.UserInfo.Info
#using (Html.BeginForm()){
#Html.LabelFor(m => m.firstname);
#Html.TextBoxFor(m => m.firstname, new { #Value = ViewBag.Firstname });
#Html.LabelFor(m => m.lastname);
#Html.TextBoxFor(m => m.lastname, new { #Value = ViewBag.Lastname });
#Html.LabelFor(m => m.email);
#Html.TextBoxFor(m => m.email, new { #Value = ViewBag.Email });
#Html.LabelFor(m => m.phone);
#Html.TextBoxFor(m => m.phone, new { #Value = ViewBag.Phone });
#Html.Hidden("username", new { #Value = ViewBag.Username });
<input type="submit" value="Submit" />}
in my controller:
[HttpPost]
[AllowAnonymous]
public ActionResult UpdatePersonal(UserInfo.Info userInfo)
{
I'm trying to use Ajax.BeginForm but without any success. I cannot get my form to work properly. My Controller Action "UpdateTest" is never called I don't know why. I followed many tutorial but still get the same problem. Thank you for your help !
My Model:
public class TestModel
{
public ObjectId _id { get; set; }
public int orange { get; set; }
public int blue { get; set; }
public int red { get; set; }
public int yellow { get; set; }
public int white { get; set; }
public float green { get; set; }
public float pink { get; set; }
}
My Action in ColorController
[HttpPost]
public void UpdateTest(TestModel tmp)
{
...
...
}
My View
#model Project.Models.TestModel
#using (Ajax.BeginForm(new AjaxOptions()
{
HttpMethod = "POST",
Url = Url.Action("UpdateTest", "Color")
}))
{
#Html.TextBoxFor(model => model._id)
#Html.TextBoxFor(model => model.orange)
#Html.TextBoxFor(model => model.blue)
#Html.TextBoxFor(model => model.red)
#Html.TextBoxFor(model => model.yellow)
#Html.TextBoxFor(model => model.white)
#Html.TextBoxFor(model => model.green)
#Html.TextBoxFor(model => model.pink)
<input type="submit" value="Submit" />
}
Javascript
<script type="text/javascript" src="/Scripts/jquery.unobtrusive-ajax.min.js">
</script>
Try it this way....
#using (Ajax.BeginForm("UpdateTest", "Color", new AjaxOptions() { HttpMethod = "POST" }))
{
#Html.TextBoxFor(model => model._id)
#Html.TextBoxFor(model => model.orange)
#Html.TextBoxFor(model => model.blue)
#Html.TextBoxFor(model => model.red)
#Html.TextBoxFor(model => model.yellow)
#Html.TextBoxFor(model => model.white)
#Html.TextBoxFor(model => model.green)
#Html.TextBoxFor(model => model.pink)
<input type="submit" value="Submit" />
}