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)
{
Related
Model
League and LeagueDivision are two model classes
public class League
{
public int Id { get; set; }
public string League1 { get; set; }
public string Icon { get; set; }
public virtual ICollection<LeagueDivision> LeagueDivisions { get; set; }
}
public class LeagueDivision
{
public int Id { get; set; }
public Nullable<int> LeagueId { get; set; }
public string Name { get; set; }
public string Icon { get; set; }
public virtual League League { get; set; }
}
public class ViewModelForHostBooster
{
[Required(ErrorMessage = "Please enter price")]
[Display(Name = "Price")]
public decimal Price { get; set; }
[Required(ErrorMessage = "Please select a league")]
[Display(Name = "League")]
public int? SelectedLeague { get; set; }
[Required(ErrorMessage = "Please select a league division")]
[Display(Name = "League Division")]
public int? SelectedLeagueDivision { get; set; }
public SelectList LeagueList { get; set; }
public SelectList LeagueDivisionList { get; set; }
}
Controller
In IndexDropdown action I am just populating view with model and validating if
the model is validated then populate the view otherwise return the view. In FetchLeagueDivision action I am selecting Id and Name properties of model class based on passed argument ID.
Can anybody guide me why a WebHttpException is happening when I run this piece of code? Here is a link of exception Http Exception Image
public class DropDownController : Controller
{
[HttpGet]
public ActionResult IndexDropDown()
{
ViewModelForHostBooster model = new ViewModelForHostBooster();
ConfigureViewModel(model);
return View(model);
}
[HttpPost]
public ActionResult IndexDropDown(ViewModelForHostBooster model)
{
if (!ModelState.IsValid)
{
ConfigureViewModel(model);
return View(model);
}
// save and redirect
return RedirectToAction("Somewhere");
}
private void ConfigureViewModel(ViewModelForHostBooster model)
{
HostBoostersDBEntities db = new HostBoostersDBEntities();
var leagues = db.Leagues.Select(x => new { Value = x.Id, Text = x.League1 }).ToList();
model.LeagueList = new SelectList(leagues, "Id", "League1");
if (model.SelectedLeague.HasValue)
{
IEnumerable<LeagueDivision> leaguedivisions = db.LeagueDivisions.Where(l => l.LeagueId == model.SelectedLeague.Value);
model.LeagueDivisionList = new SelectList(leaguedivisions, "Id", "Name");
}
else
{
model.LeagueDivisionList = new SelectList(Enumerable.Empty<SelectListItem>());
}
}
}
View
#model HostBooster.Models.ViewModelForHostBooster
#using (Html.BeginForm())
{
<div>
#Html.LabelFor(m => m.Price)
#Html.TextBoxFor(m => m.Price)
#Html.ValidationMessageFor(m => m.Price)
</div>
<div>
#Html.LabelFor(m => m.SelectedLeague)
exception is occurring here #Html.DropDownListFor(m => m.SelectedLeague, Model.LeagueList)
#Html.DropDownListFor(m => m.SelectedLeague, Model.LeagueList)
#Html.ValidationMessageFor(m => m.SelectedLeague)
</div>
<div>
#Html.LabelFor(m => m.SelectedLeagueDivision)
#Html.DropDownListFor(m => m.SelectedLeagueDivision, Model.LeagueDivisionList)
#Html.ValidationMessageFor(m => m.SelectedLeagueDivision)
</div>
<input type="submit" value="save" />
}
In view Model.LeagueList is null. It should not be null.
if edit view code like this(for example), Works well:
<body>
#using (Html.BeginForm())
{
List<SelectListItem> listItems = new List<SelectListItem>();
listItems.Add(new SelectListItem
{
Text = "Example1",
Value = "Example1"
});
listItems.Add(new SelectListItem
{
Text = "Example2",
Value = "Example2",
Selected = true
});
listItems.Add(new SelectListItem
{
Text = "Example3",
Value = "Example3"
});
<div>
#Html.LabelFor(m => m.Price)
#Html.TextBoxFor(m => m.Price)
#Html.ValidationMessageFor(m => m.Price)
</div>
<div>
#Html.LabelFor(m => m.SelectedLeague)
#Html.DropDownListFor(m => m.SelectedLeague, listItems)
#Html.ValidationMessageFor(m => m.SelectedLeague)
</div>
<div>
#Html.LabelFor(m => m.SelectedLeagueDivision)
#Html.DropDownListFor(m => m.SelectedLeagueDivision, Model.LeagueDivisionList)
#Html.ValidationMessageFor(m => m.SelectedLeagueDivision)
</div>
<input type="submit" value="save" />
}
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!
I have View like this:
#model MVCApp.Models.User
#{
ViewBag.Title = "EditUser";
}
<h2>Edycja użytkownika</h2>
#using (Ajax.BeginForm("SaveUser", "My", new AjaxOptions { UpdateTargetId = "Result" }))
{
<fieldset>
<legend>Zmień dane użytkownika</legend>
<div id="EditUserForm">
<div>
#Html.LabelFor(m => Model.Login)
#Html.TextBoxFor(m => Model.Login)
</div>
<div>
#Html.LabelFor(m => Model.Password)
#Html.TextBoxFor(m => Model.Password)
</div>
<div>
#Html.LabelFor(m => Model.Name)
#Html.TextBoxFor(m => Model.Name)
</div>
<div>
#Html.LabelFor(m => Model.Surname)
#Html.TextBoxFor(m => Model.Surname)
</div>
<div>
#Html.LabelFor(m => Model.UserRole.Role)
#Html.TextBoxFor(m => Model.UserRole.Role)
</div>
<input type="submit" value="Zapisz zmiany" />
#Html.HiddenFor(m => Model.UserRole)
#Html.HiddenFor(m => Model.UserRoleID)
#Html.HiddenFor(m => Model.UserID)
</div>
</fieldset>
<div id="Result"></div>
#Html.ValidationSummary(true)
}
and method in MyController like this:
[HttpPost]
public ActionResult SaveUser(User user, UserRole role)
{
//code here
}
but object role is not passed, either user.UserRole.
My User model class:
namespace MVCApp.Models
{
public partial class User
{
public User()
{
this.Factures = new HashSet<Facture>();
this.Settings = new HashSet<Setting>();
this.Companies = new HashSet<Company>();
}
public int UserID { get; set; }
public Nullable<int> UserRoleID { get; set; }
public string Login { get; set; }
public string Password { get; set; }
public string Name { get; set; }
public string Surname { get; set; }
public virtual ICollection<Facture> Factures { get; set; }
public virtual ICollection<Setting> Settings { get; set; }
public virtual UserRole UserRole { get; set; }
public virtual ICollection<Company> Companies { get; set; }
}
}
And Role model class:
namespace MVCApp.Models
{
public partial class UserRole
{
public UserRole()
{
this.Users = new HashSet<User>();
}
public int UserRoleID { get; set; }
public string Role { get; set; }
public virtual ICollection<User> Users { get; set; }
}
}
so, How can I pass models like this, which has other reference types inside?
The following line in your view make no sense
#Html.HiddenFor(m => Model.UserRole)
UserRole is a complex object, and depending on whether you have overridden its .ToString() method, it will render <input ... value="MVCApp.Models.UserRole" /> so when this posts back the DefaultModelBinder is trying to do model.UserRole = "MVCApp.Models.UserRole" which of course fails and the property is therefore null
Remove it, and instead bind to the properties of UserRole that you want posted back - as you have done with #Html.TextBoxFor(m => Model.UserRole.Role). For example #Html.HiddenFor(m => Model.UserRole.UserRoleID) but you already seem to have bound this with #Html.HiddenFor(m => Model.UserRoleID) so it might not be necessay to repeat it.
you can create your own submitting mechanism. Just use $.ajax and pass in its data property all your values. A bit more js code, but a lot more flexibility.
My entities:
public class Meal
{
[HiddenInput(DisplayValue = false)]
public int Id { get; set; }
[Required(ErrorMessage = "Proszę podać nazwę posiłku")]
public string Name { get; set; }
[Required(ErrorMessage = "Proszę podać ilość białka")]
[Range(0.00, double.MaxValue, ErrorMessage = "Proszę podać dodatnią ilość.")]
public double Protein { get; set; }
[Required(ErrorMessage = "Proszę podać ilość węglowodanów")]
[Range(0.00, double.MaxValue, ErrorMessage = "Proszę podać dodatnią ilość.")]
public double Carbohydrates { get; set; }
[Required(ErrorMessage = "Proszę podać ilość tłuszczy")]
[Range(0.00, double.MaxValue, ErrorMessage = "Proszę podać dodatnią ilość.")]
public double Fat { get; set; }
[Required(ErrorMessage = "Proszę podać ilość kalorii")]
[Range(0.00, double.MaxValue, ErrorMessage = "Proszę podać dodatnią ilość.")]
public double Calories { get; set; }
}
public class EatenMeal
{
public int Id { get; set; }
public virtual Meal Meal { get; set; }
public virtual MealType MealType { get; set; }
public double Serving { get; set; }
public string Username { get; set; }
public DateTime Date { get; set; }
}
public class MealType
{
public int Id { get; set; }
public string Name { get; set; }
}
In MealController's view MealList which displays meals from datebase. And there is a button "Add" which refers to action AddEatenMeal in EatenMealController.
public ActionResult AddEatenMeal(int id)
{
var meal = mealRepository.GetMeal(id);
EatenMeal eatenMeal = new EatenMeal() { Meal = meal, Username = User.Identity.Name };
return View(eatenMeal);
}
[HttpPost]
public ActionResult AddEatenMeal(EatenMeal eatenMeal)
{
if(ModelState.IsValid)
{
eatenMealRepository.AddEatenMeal(eatenMeal);
RedirectToAction("Index", "Home");
}
return RedirectToAction("Index", "Home");
}
I am creating there object EatenMeal and partially initializing this object. Then I am passing this object to View to further initializing.
#model Domain.Entities.EatenMeal
#{
ViewBag.Title = "Dodawanie posiłku do dziennika";
}
#using (Html.BeginForm("AddEatenMeal","EatenMeal", FormMethod.Post, new {#class = "form"}))
{
#Html.HiddenFor(x => x.Meal.Name)
#Html.HiddenFor(x => x.Username)
#Html.HiddenFor(x => x.Meal.Calories)
#Html.HiddenFor(x => x.Meal.Carbohydrates)
#Html.HiddenFor(x => x.Meal.Fat)
#Html.HiddenFor(x => x..Meal.Protein)
#Html.HiddenFor(x => x.Meal.Id)
#Html.HiddenFor(x=>x.Username)
<div class="form-group">
#Html.Label("Nazwa posiłku")
#Html.Label(Model.Meal.Name, new { #class = "form-control" })
</div>
<div class="form-group">
#Html.Label("Porcja (g)")
#Html.TextBoxFor(x => x.Serving, new { #class = "form-control" })
</div>
<div class="form-group">
#Html.Label("Typ posiłku")
#Html.DropDownListFor(x=>x.MealType)????
</div>
<div class="form-group">
#Html.Label("Data spożycia")
#Html.TextBoxFor(x => x.Date, new { #class = "form-control", #id="date-eaten", #Value=DateTime.Today.ToShortDateString()})
</div>
<input type="submit" class="btn btn-info" value="Dodaj" />
}
Now I have a question. Is it correct to hiding fields? I don't know how I can save data from first controller to second in other way.
And is a second question. How I can make DropDownListFor for property MealTye in EatenMeal?
Rather than sending and receiving a whole lot of unused data across the wire and opening yourself to over posting attack, create a view model that represents what you want to display and edit. See What is a view model in MVC?
View model
public class EatenMealVM
{
public int MealID { get; set; }
[Display(Name="Nazwa posiłku")]
public string MealName { get; set; }
[Display(Name = "Typ posiłku")]
[Required(ErrorMessage = "Please select a meal")]
public int? MealTypeID { get; set; }
[Display(Name = "Porcja (g)")]
public double Serving { get; set; } // is this really double?
[Display(Name = "Data spożycia")]
[DataType(DataType.Date)]
public DateTime Date { get; set; }
public SelectList MealTypeList { get; set; }
}
Controller
public ActionResult AddEatenMeal(int id)
{
var meal = mealRepository.GetMeal(id);
var mealTypes = // get the list of meal types from the database
EatenMealVM model = new EatenMealVM()
{
MealID = meal.Id,
MealName = meal.Name,
MealTypeList = new SelectList(mealTypes, "ID", "Name")
};
return View(model);
}
View
#model EatenMealVM
....
#using (Html.BeginForm())
{
#Html.HiddenFor(m => m.MealID)
#Html.DisplayNameFor(m => m.MealName)
#Html.DisplayFor(m => m.MealName)
#Html.LabelFor(m => m.MealTypeID)
#Html.DropDownListFor(m => m.MealTypeID, Model.MealTypeList, "--Please select--")
#Html.ValidationMessageFor(m => m.MealTypeID)
#Html.LabelFor(m => m.Serving)
#Html.TextBoxFor(m => m.Serving, new { #class = "form-control")
#Html.ValidationMessageFor(m => m.Serving)
#Html.LabelFor(m => m.Date)
#Html.TextBoxFor(m => m.Date)
#Html.ValidationMessageFor(m => m.Date, new { #class = "form-control" })
<input type="submit" class="btn btn-info" value="Dodaj" />
}
Post method
[HttpPost]
public ActionResult AddEatenMeal(EatenMealVM model)
{
if (!ModelState.IsValid)
{
var mealTypes = // get the list of meal types from the database
model.MealTypeList = new SelectList(mealTypes, "ID", "Name");
return View(model);
}
// Initialize new EatenMeal class
// Map properties from view model (including setting user name)
// Save and redirect
}
Note also the use of [Display] attribute and #Html.LabelFor(). Currently you not creating 'real' labels (they are not associated with the corresponding control)
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" />
}