Checkboxlist - on Post: Create - NullReferenceException - nullreferenceexception

StudentModel.
namespace mvcApp.Models
{
public class StudentModel
{
[Display(Name = "First Name")]
public string FirstName { get; set; }
[Display(Name = "Last Name")]
public string LastName { get; set; }
[Display(Name = "Email Address")]
public string EmailAddress { get; set; }
public List<SchoolOrganization> Organizations { get; set; }
}
public class SchoolOrganization
{
public string Name { get; set; }
public bool IsInvolved { get; set; }
}
}
Student is involved in multiple organizations.
Controller
namespace mvcApp.Controllers
{
public class HomeController : Controller
{
public ActionResult Index()
{
ViewBag.Message = "Modify this template to jump-start your ASP.NET MVC application.";
return View();
}
public ActionResult StudentInformation()
{
// populate student with data
var student = new StudentModel() { FirstName = "Joe", LastName = "Doe", EmailAddress = "jdoe#hotmail.com"};
// Populate with Organizations
student.Organizations = new List<SchoolOrganization>();
student.Organizations.Add(new SchoolOrganization() { Name = "Math Club", IsInvolved = true});
student.Organizations.Add(new SchoolOrganization() { Name = "Chess Club", IsInvolved = false });
student.Organizations.Add(new SchoolOrganization() { Name = "Football", IsInvolved = true });
return View(student);
}
**[HttpPost]
public ActionResult StudentInformation(StudentModel student)
{
Response.Write("Name: " + student.FirstName);
foreach (var o in student.Organizations)
{
Response.Write(o.Name + " : " + o.IsInvolved.ToString());
}
return View();
}**
}
}
Data will be eventually populated from database.
View
#model mvcApp.Models.StudentModel
#{
ViewBag.Title = "StudentInformation";
}
<h2>StudentInformation</h2>
#using (Html.BeginForm()) {
#Html.AntiForgeryToken()
#Html.ValidationSummary(true)
<fieldset>
<legend>StudentModel</legend>
<div class="editor-label">
#Html.LabelFor(model => model.FirstName)
</div>
<div class="editor-field">
#Html.EditorFor(model => model.FirstName)
#Html.ValidationMessageFor(model => model.FirstName)
</div>
<div class="editor-label">
#Html.LabelFor(model => model.LastName)
</div>
<div class="editor-field">
#Html.EditorFor(model => model.LastName)
#Html.ValidationMessageFor(model => model.LastName)
</div>
<div class="editor-label">
#Html.LabelFor(model => model.EmailAddress)
</div>
<div class="editor-field">
#Html.EditorFor(model => model.EmailAddress)
#Html.ValidationMessageFor(model => model.EmailAddress)
</div>
<div>
<table>
<tr>
<td>Organization Name</td><td>Is Involved</td>
</tr>
#for (int i = 0; i < Model.Organizations.Count; i++) <== System.NullReferenceException here
{
#Html.HiddenFor(m => m.Organizations[i].IsInvolved)
<tr>
<td>#Html.DisplayFor(m => m.Organizations[i].Name)</td>
<td>#Html.CheckBoxFor(m => m.Organizations[i].IsInvolved)</td>
</tr>
}
</table>
</div>
<p>
<input type="submit" value="Save" />
</p>
</fieldset>
}
The above code displays fine with HttGet. However, when i try to update i get System.NullReferenceException. https://www.dropbox.com/s/dz0bg3hkd0yq8e3/studentInformation.png?dl=0
Can anyone please help figure it what's going on?
Thank you.

In the code sample you have provided; the HomeController's [HttpPost] ActionResult for StudentInformation does not create and pass a new instance of the updated object model to the view, but instead runs a basic debug.writeline routine. As a result the dependent view for the [HttpPost] view of "StudentInformation.cshtml", does not receive a populated instance of the updated model...
Setting a breakpoint on the first line of the model for the "StudentInformation.cshtml" page and running the application will demonstrate that the model referenced at the top of the page, has no data within it...
This is why the [HttpPost] version of the page simply renders the blank model, without any altered data values you may have created, UNTIL it gets to the section where the view is dependent on a count of new data values which must be present within the model that is called at first line of the page... to continue.
An empty data model set results in a null reference because there are no values to count within it.
In order to view an updated group of settings, The [HttpPost] version of the view model must be passed an instance of the model that returns the new information as in "return View(nameOfViewDataSet)" (you build a data set again, and pass it as a new version of the model, with revised form data present).
Until there is data passed via the return View statement relative to the [HttpPost] version of the StudentInformation ActionResult, to the actual view, there will be no display data, and the count function will continue to return a null value.
I hope that is helpful.

Related

Update model one of the properties of List type is null upon submit

I have Model class "Customer". One of its properties is a collection of object lets say "Order". I want that during edit I can modify the list of orders associated with the selected Customer that I want to update but when I submit the modified customer and modified orders the order object is null. Please help how can I send the modified orders on edit. Here's my code
Class
public class Customer
{
public int CustomerId { get; set; }
public string CustomerName { get; set; }
public List<Order> Orders { get; set; }
}
public class Order
{
public int OrderId { get; set; }
public string OrderName { get; set; }
}
Edit View
#model MVCTestApp.Models.Customer
#{
ViewBag.Title = "Edit";
}
#using (Html.BeginForm())
{
#Html.ValidationSummary(true)
<fieldset>
<legend>Customer</legend>
#Html.HiddenFor(model => model.CustomerId)
<div class="editor-label">
#Html.LabelFor(model => model.CustomerName)
</div>
<div class="editor-field">
#Html.EditorFor(model => model.CustomerName)
#Html.ValidationMessageFor(model => model.CustomerName)
</div>
#foreach (var order in Model.Orders)
{
<div class="editor-label">
#Html.Label(order.OrderName)
</div>
<div class="editor-field">
#Html.Editor(order.OrderName, new { id = order.OrderId })
</div>
}
<p><input type="submit" value="Save" /> </p>
</fieldset>
}
Submitted Edited View
Use a for-loop instead of foreach:
#for (var i=0;i<Model.Orders.Count();i++)
{
<div class="editor-label">
#Html.Label(Model.Orders[i].OrderName)
</div>
<div class="editor-field">
#Html.EditorFor(m=> Model.Orders[i].OrderName)
</div>
}
The reason for this issue can be easily seen on the rendered html of the foreach approach. The names of the elements do not have an index and they all have the same name. The model binder cannot infer how to pass it to your controller. Using a for-loop you are somewhat forcing (if that's the right term) the markup/html to have an index on your Orders objects. Having done that, the model binder can now properly map your inputs to the Orders field.
Oh by the way. Now that you are using a for-loop you need to verify that your Orders collection is not null. But I'm sure you can easily do that.
I'd recommend you to get orders in action like this:(check if order_OrderName is the name of the input filed in form, see the source for example with firebug or something)
public ActionResult Edit(int id, string[] order_OrderName , Customer customer )
{
//////
}

Asp.net mvc 3 model doesn't get automatically bind?

I'm studying asp.net mvc 3 right now and I'm following this tutorial Contoso University
http://www.asp.net/mvc/tutorials/getting-started-with-ef-using-mvc/handling-concurrency-with-the-entity-framework-in-an-asp-net-mvc-application
I'm in this part where editing a model is handled with Optimistic Concurrency
I'm aware that by using something like
[HttpPost]
public ActionResult Edit(Department department)
the model will automatically be binded, even without a hidden field for the id of the department to be edited, and the edit will not fail.
But whenever I try to remove the two hiddenfields in the view of this one:
#model MvcContosoUniversity.Models.Department
#{
ViewBag.Title = "Edit";
}
<h2>Edit</h2>
<script src="#Url.Content("~/Scripts/jquery.validate.min.js")" type="text/javascript"></script>
<script src="#Url.Content("~/Scripts/jquery.validate.unobtrusive.min.js")" type="text/javascript"></script>
#using (Html.BeginForm()) {
#Html.ValidationSummary(true)
<fieldset>
<legend>Department</legend>
#Html.HiddenFor(model => model.DepartmentID)
#Html.HiddenFor(model => model.Timestamp)
<div class="editor-label">
#Html.LabelFor(model => model.Name)
</div>
<div class="editor-field">
#Html.EditorFor(model => model.Name)
#Html.ValidationMessageFor(model => model.Name)
</div>
<div class="editor-label">
#Html.LabelFor(model => model.Budget)
</div>
<div class="editor-field">
#Html.EditorFor(model => model.Budget)
#Html.ValidationMessageFor(model => model.Budget)
</div>
<div class="editor-label">
#Html.LabelFor(model => model.StartDate)
</div>
<div class="editor-field">
#Html.EditorFor(model => model.StartDate)
#Html.ValidationMessageFor(model => model.StartDate)
</div>
<div class="editor-label">
#Html.LabelFor(model => model.InstructorID, "Administrator")
</div>
<div class="editor-field">
#Html.DropDownList("InstructorID", String.Empty)
#Html.ValidationMessageFor(model => model.InstructorID)
</div>
<p>
<input type="submit" value="Save" />
</p>
</fieldset>
}
<div>
#Html.ActionLink("Back to List", "Index")
</div>
I get an error in the controller, here's the code for the controller:
// GET: /Department/Edit/5
public ActionResult Edit(int id)
{
Department department = db.Departments.Find(id);
ViewBag.InstructorID = new SelectList(db.Instructors, "InstructorID", "FullName", department.InstructorID);
return View(department);
}
//
// POST: /Department/Edit/5
[HttpPost]
public ActionResult Edit(Department department)
{
try
{
if (ModelState.IsValid)
{
db.Entry(department).State = EntityState.Modified;
db.SaveChanges();
return RedirectToAction("Index");
}
}
catch (DbUpdateConcurrencyException ex)
{
var entry = ex.Entries.Single();
//Another option is to put the try-catch inside a function
try
{
var databaseValues = (Department)entry.GetDatabaseValues().ToObject();
var clientValues = (Department)entry.Entity;
if (databaseValues.Name != clientValues.Name)
ModelState.AddModelError("Name", "Current value: "
+ databaseValues.Name);
if (databaseValues.Budget != clientValues.Budget)
ModelState.AddModelError("Budget", "Current value: "
+ String.Format("{0:c}", databaseValues.Budget));
if (databaseValues.StartDate != clientValues.StartDate)
ModelState.AddModelError("StartDate", "Current value: "
+ String.Format("{0:d}", databaseValues.StartDate));
if (databaseValues.InstructorID != clientValues.InstructorID)
ModelState.AddModelError("InstructorID", "Current value: "
+ db.Instructors.Find(databaseValues.InstructorID).FullName);
ModelState.AddModelError(string.Empty, "The record you attempted to edit "
+ "was modified by another user after you got the original value. The "
+ "edit operation was canceled and the current values in the database "
+ "have been displayed. If you still want to edit this record, click "
+ "the Save button again. Otherwise click the Back to List hyperlink.");
department.Timestamp = databaseValues.Timestamp;
}
catch(NullReferenceException e)
{
ModelState.AddModelError("","Error \n "+e.Message);
}
}
catch (DataException)
{
//Log the error (add a variable name after Exception)
ModelState.AddModelError(string.Empty, "Unable to save changes. Try again, and if the problem persists contact your system administrator.");
}
ViewBag.InstructorID = new SelectList(db.Instructors, "InstructorID", "FullName", department.InstructorID);
return View(department);
}
Here is the code for the model:
public class Department
{
public int DepartmentID { get; set; }
[Required(ErrorMessage = "Department name is required.")]
[MaxLength(50)]
public string Name { get; set; }
[DisplayFormat(DataFormatString = "{0:c}")]
[Required(ErrorMessage = "Budget is required.")]
[Column(TypeName = "money")]
public decimal? Budget { get; set; }
[DisplayFormat(DataFormatString = "{0:d}", ApplyFormatInEditMode = true)]
[Required(ErrorMessage = "Start date is required.")]
public DateTime StartDate { get; set; }
[Display(Name = "Administrator")]
public int? InstructorID { get; set; }
public virtual Instructor Administrator { get; set; }
public virtual ICollection<Course> Courses { get; set; }
[Timestamp]
public Byte[] Timestamp { get; set; }
}
Is it possible to make it work without using hiddenfields?
Sir/Ma'am your answers would be of great help. Thank you++
Based on your HttpPost action signature, no, this isn't possible. You're performing an Edit so it will need the Id of the row that is being updated. Since you're not mapping the Id in the action method signature, and the hidden fields holding that information aren't there, the id will never get mapped to the Department model. The result being that you would try to perform an update without a row id.
EDIT: You could modify your action signature like so: Edit(int id, Department department), but then you'd have to manually set the department.Id to the id passed and that would seem to make the model somewhat disjointed.

How to make Optimistic Concurrency editing in Asp.net mvc 3 without using hiddenfields in the view?

I'm studying asp.net mvc 3 right now and I'm following this tutorial Contoso University
http://www.asp.net/mvc/tutorials/getting-started-with-ef-using-mvc/handling-concurrency-with-the-entity-framework-in-an-asp-net-mvc-application
I'm in this part where editing a model is handled with Optimistic Concurrency
I'm aware that by using something like
[HttpPost]
public ActionResult Edit(Department department)
the model will automatically be binded, even without a hidden field for the id of the department to be edited, and the edit will not fail.
But whenever I try to remove the two hiddenfields in the view of this one:
#model MvcContosoUniversity.Models.Department
#{
ViewBag.Title = "Edit";
}
<h2>Edit</h2>
<script src="#Url.Content("~/Scripts/jquery.validate.min.js")" type="text/javascript"></script>
<script src="#Url.Content("~/Scripts/jquery.validate.unobtrusive.min.js")" type="text/javascript"></script>
#using (Html.BeginForm()) {
#Html.ValidationSummary(true)
<fieldset>
<legend>Department</legend>
#Html.HiddenFor(model => model.DepartmentID)
#Html.HiddenFor(model => model.Timestamp)
<div class="editor-label">
#Html.LabelFor(model => model.Name)
</div>
<div class="editor-field">
#Html.EditorFor(model => model.Name)
#Html.ValidationMessageFor(model => model.Name)
</div>
<div class="editor-label">
#Html.LabelFor(model => model.Budget)
</div>
<div class="editor-field">
#Html.EditorFor(model => model.Budget)
#Html.ValidationMessageFor(model => model.Budget)
</div>
<div class="editor-label">
#Html.LabelFor(model => model.StartDate)
</div>
<div class="editor-field">
#Html.EditorFor(model => model.StartDate)
#Html.ValidationMessageFor(model => model.StartDate)
</div>
<div class="editor-label">
#Html.LabelFor(model => model.InstructorID, "Administrator")
</div>
<div class="editor-field">
#Html.DropDownList("InstructorID", String.Empty)
#Html.ValidationMessageFor(model => model.InstructorID)
</div>
<p>
<input type="submit" value="Save" />
</p>
</fieldset>
}
<div>
#Html.ActionLink("Back to List", "Index")
</div>
I get an error in the controller, here's the code for the controller:
// GET: /Department/Edit/5
public ActionResult Edit(int id)
{
Department department = db.Departments.Find(id);
ViewBag.InstructorID = new SelectList(db.Instructors, "InstructorID", "FullName", department.InstructorID);
return View(department);
}
//
// POST: /Department/Edit/5
[HttpPost]
public ActionResult Edit(Department department)
{
try
{
if (ModelState.IsValid)
{
db.Entry(department).State = EntityState.Modified;
db.SaveChanges();
return RedirectToAction("Index");
}
}
catch (DbUpdateConcurrencyException ex)
{
var entry = ex.Entries.Single();
//Another option is to put the try-catch inside a function
try
{
var databaseValues = (Department)entry.GetDatabaseValues().ToObject();
var clientValues = (Department)entry.Entity;
if (databaseValues.Name != clientValues.Name)
ModelState.AddModelError("Name", "Current value: "
+ databaseValues.Name);
if (databaseValues.Budget != clientValues.Budget)
ModelState.AddModelError("Budget", "Current value: "
+ String.Format("{0:c}", databaseValues.Budget));
if (databaseValues.StartDate != clientValues.StartDate)
ModelState.AddModelError("StartDate", "Current value: "
+ String.Format("{0:d}", databaseValues.StartDate));
if (databaseValues.InstructorID != clientValues.InstructorID)
ModelState.AddModelError("InstructorID", "Current value: "
+ db.Instructors.Find(databaseValues.InstructorID).FullName);
ModelState.AddModelError(string.Empty, "The record you attempted to edit "
+ "was modified by another user after you got the original value. The "
+ "edit operation was canceled and the current values in the database "
+ "have been displayed. If you still want to edit this record, click "
+ "the Save button again. Otherwise click the Back to List hyperlink.");
department.Timestamp = databaseValues.Timestamp;
}
catch(NullReferenceException e)
{
ModelState.AddModelError("","Error \n "+e.Message);
}
}
catch (DataException)
{
//Log the error (add a variable name after Exception)
ModelState.AddModelError(string.Empty, "Unable to save changes. Try again, and if the problem persists contact your system administrator.");
}
ViewBag.InstructorID = new SelectList(db.Instructors, "InstructorID", "FullName", department.InstructorID);
return View(department);
}
Here is the code for the model:
public class Department
{
public int DepartmentID { get; set; }
[Required(ErrorMessage = "Department name is required.")]
[MaxLength(50)]
public string Name { get; set; }
[DisplayFormat(DataFormatString = "{0:c}")]
[Required(ErrorMessage = "Budget is required.")]
[Column(TypeName = "money")]
public decimal? Budget { get; set; }
[DisplayFormat(DataFormatString = "{0:d}", ApplyFormatInEditMode = true)]
[Required(ErrorMessage = "Start date is required.")]
public DateTime StartDate { get; set; }
[Display(Name = "Administrator")]
public int? InstructorID { get; set; }
public virtual Instructor Administrator { get; set; }
public virtual ICollection<Course> Courses { get; set; }
[Timestamp]
public Byte[] Timestamp { get; set; }
}
Is it possible to make it work without using hiddenfields?
Sir/Ma'am your answers would be of great help. Thank you++
You need to have the id value coming from somewhere, or that entity can't be saved... how does EF know what ID it's saving without it?
It doesn't have to be via hidden field; It's probably there in the query string from the initial GET request for the edit action.

Retrieve a subset of a ViewModel from a RenderPartial on POST

I have a ViewModel which contains a child ViewModel. In a strongly typed Viewed of the parent, I want to RenderPartial on the child, and have results persist following POST.
But the child fields are always null.
This should work, shouldn't it? I am fairly new to MVC, hopefully I'm missing something simple. Hopefully someone can point it out!
Thanks!
Example
ViewModels
public class EggBoxViewModel
{
public string Brand { get; set; }
public int Price { get; set; }
public EggViewModel Egg { get; set; }
}
public class EggViewModel
{
public string Size { get; set; }
public bool IsBroken { get; set; }
}
Controller
public ActionResult Demo()
{
EggBoxViewModel eggBox = new EggBoxViewModel();
eggBox.Brand = "HappyEggs";
eggBox.Price = 3;
EggViewModel egg = new EggViewModel();
egg.Size = "Large";
egg.IsBroken = false;
eggBox.Egg = egg;
return View(eggBox);
}
[HttpPost]
public ActionResult Demo(EggBoxViewModel eggBox)
{
// here, eggBox.Egg is null
}
Views
"Demo"
#model MvcApplication1.ViewModels.EggBoxViewModel
#using (Html.BeginForm())
{
<h2>EggBox:</h2>
<p>
#Html.LabelFor(model => model.Brand)
#Html.EditorFor(model => model.Brand)
</p>
<p>
#Html.LabelFor(model => model.Price)
#Html.EditorFor(model => model.Price)
</p>
<p>
#{Html.RenderPartial("_Egg", Model.Egg);}
</p>
<input type="submit" value="Submit" />
}
"_Egg" (Partial)
#model MvcApplication1.ViewModels.EggViewModel
<h2>Egg</h2>
<p>
#Html.LabelFor(model => model.Size)
#Html.EditorFor(model => model.Size)
</p>
<p>
#Html.LabelFor(model => model.IsBroken)
#Html.CheckBoxFor(model => model.IsBroken)
</p>
Use an Editor Template, in most cases they're better for rendering child objects or collections. In your Views\Shared folder create a new folder called EditorTemplates if you don't already have one. Add a new partial view called EggViewModel and use the same code as in your partial view. This is the bit of magic that renders and names all your fields correctly. It will also handle a collection of EggViewModels without a for each loop as the Editor template will automatically render all the items passed in a collection:
#model MvcApplication1.ViewModels.EggViewModel
<h2>Egg</h2>
<p>
#Html.LabelFor(model => model.Size)
#Html.EditorFor(model => model.Size)
</p>
<p>
#Html.LabelFor(model => model.IsBroken)
#Html.CheckBoxFor(model => model.IsBroken)
</p>
Then in your Demo View use your new Editor Template instead of the partial:
<p>
#Html.EditorFor(x => x.Egg)
</p>
Here are the fields that are rendered:
In the post back you can that the EggViewModel is now part of the EggBoxViewModel:
Also in the ModelState you can see that the Egg fields are prefixed with the property name used in the EggBoxViewModel which makes them a subset of EggBox.
And...the great thing is that if you want to have a collection of Eggs in your EggBox it's really easy...just make your Egg property on EggBoxViewModel a collection:
public class EggBoxViewModel
{
public string Brand { get; set; }
public int Price { get; set; }
public ICollection<EggViewModel> Eggs { get; set; }
}
Add a second egg:
public ActionResult Demo()
{
EggBoxViewModel eggBox = new EggBoxViewModel();
eggBox.Brand = "HappyEggs";
eggBox.Price = 3;
EggViewModel egg = new EggViewModel();
egg.Size = "Large";
egg.IsBroken = false;
EggViewModel egg2 = new EggViewModel();
egg2.Size = "Medium";
egg2.IsBroken = false;
eggBox.Eggs = new List<EggViewModel>();
eggBox.Eggs.Add(egg);
eggBox.Eggs.Add(egg2);
return View(eggBox);
}
Change your View to render x.Eggs instead of x.Egg:
<p>
#Html.EditorFor(x => x.Eggs)
</p>
Then on post back you'll see there are 2 Eggs posted back:
The field names have automatically been indexed and named to create a collection of Eggs:
you'll have to change your partial view model to EggBoxViewModel so that the Egg object is exposed on the view. i.e:
#model MvcApplication1.ViewModels.EggBoxViewModel
<h2>
Egg</h2>
<p>
#Html.LabelFor(model => model.Egg.Size)
#Html.EditorFor(model => model.Egg.Size)
</p>
<p>
#Html.LabelFor(model => model.Egg.IsBroken)
#Html.CheckBoxFor(model => model.Egg.IsBroken)
</p>
thus, you'd call it from the main view as:
#{Html.RenderPartial("_Egg", Model);}
you should now see the Egg object in your model being returned in the HttpPost action.
[Update method 2]
ok, really quick edit!! You can keep everything the same as initially and try this in your partial (i'm not 100% certain that this will work tho):
#model MvcApplication1.ViewModels.EggViewModel
<h2>
Egg</h2>
<p>
#Html.LabelFor(model => model.Size)
#Html.Editor("Egg.Size", Model.Size)
</p>
<p>
#Html.LabelFor(model => model.IsBroken)
#Html.CheckBox("Egg.IsBroken", Model.IsBroken)
</p>
here, I just use #Html.Editor() and input the required model name, rather than #Html.EditorFor(). Ok, gorra dash... train to 'cache' ;-)

How to update a domain object with ViewModel and AutoMapper using Entity framework?

How do i update a domain object with ViewModel with AutoMapper using Entity framework?
I have a View to edit a Question entity.
This is my Edit action:
public ActionResult Edit(int id)
{
var question = db.Question.Single(q => q.question_id == id);
Mapper.CreateMap<Question, EditQuestionViewModel>();
EditQuestionViewModel eqvm = Mapper.Map<Question, EditQuestionViewModel>(question);
eqvm.QuestionTypes = new SelectList(db.Question_Type, "type_code", "type_description", question.type_code);
eqvm.Categories = new SelectList(db.Category, "category_id", "category_name", question.category_id);
eqvm.Visibility = new SelectList(new Dictionary<int, string> {
{ 1, "Ja"},
{ 0, "Nej"}
}, "Key", "Value");
return View(eqvm);
}
And my ViewModel looks like this:
public class EditQuestionViewModel
{
public int question_id { get; set; }
public string question_wording { get; set; }
public bool visible { get; set; }
public int question_number { get; set; }
public string help_text { get; set; }
public Category Category { get; set; }
public Question_Type Question_Type { get; set; }
public string SelectedCategory { get; set; }
public string SelectedQuestionType { get; set; }
public SelectList Categories { get; set; }
public SelectList QuestionTypes { get; set; }
public SelectList Visibility { get; set; }
public string RefUrl { get; set; }
}
This is the View:
#using (Html.BeginForm("Edit", "AdminQuestion", FormMethod.Post))
{
#Html.ValidationSummary(true)
<fieldset>
<legend>Spørgsmål</legend>
<div class="editor-label">
#Html.LabelFor(model => model.question_wording, "Spørgsmål")
</div>
<div class="editor-field">
#Html.TextAreaFor(model => model.question_wording, new { #class = "required", rows = 3, cols = 50 })
#Html.ValidationMessageFor(model => model.question_wording)
</div>
<div class="editor-label">
#Html.LabelFor(model => model.SelectedCategory, "Hvilken kategori tilhører dette spørgsmål?")
</div>
<div class="editor-field">
#Html.DropDownListFor(model => model.SelectedCategory, Model.Categories)
#Html.ValidationMessageFor(model => model.SelectedCategory)
</div>
<div class="editor-label">
#Html.LabelFor(x => x.SelectedQuestionType, "Spørgsmålstype")
</div>
<div class="editor-field">
#Html.DropDownListFor(model => model.SelectedQuestionType, Model.QuestionTypes)
#Html.ValidationMessageFor(model => model.SelectedQuestionType)
</div>
<div class="editor-label">
#Html.LabelFor(model => model.visible, "Skal dette spørgsmål være synligt?")
</div>
<div class="editor-field">
#Html.DropDownListFor(model => model.visible, Model.Visibility)
#Html.ValidationMessageFor(model => model.visible)
</div>
<div class="editor-label">
#Html.LabelFor(model => model.question_number, "Hvilket nummer har spørgsmålet inden for sin kategori?")
</div>
<div class="editor-field">
#Html.TextBoxFor(model => model.question_number, new { #class = "required digits" })
#Html.ValidationMessageFor(model => model.question_number)
</div>
<div class="editor-label">
#Html.LabelFor(model => model.help_text, "Hjælpetekst som hjælper brugeren med at forstå spørgsmålet:")
</div>
<div class="editor-field">
#Html.TextAreaFor(model => model.help_text, new { rows = 20, cols = 50 })
#Html.ValidationMessageFor(model => model.help_text)
</div>
<br />
<input type="submit" value="Gem" />
</fieldset>
How do i update the entity when i submit the form ?
How should the mapping between the ViewModel and EF Model look like, using AutoMapper?
The properties
public string SelectedCategory { get; set; }
public string SelectedQuestionType { get; set; }
In the ViewModel are supposed to be linked with category_id and type_code in the EF model
Also notice the property
public bool visible { get; set; }
I use BIT in my database. Will this work with the values 0 and 1, which is use in the SelectList?
Thanks!
you would need to get the object from entity framework, and then use automapper like this:
var item = repository.getbyid(model.Id);
_mappingEngine.Map(viewModel, item);
repository.save(item);
When you submit your form, you need to have an action on your controller that will handle the post to the server.
So in addition to the Edit action you currently have, you will need to have another action defined like so:
[HttpPost]
public ActionResult Edit(EditQuestionViewModel model)
{
//Do the mapping to from your ViewModel to the EF model here
return View();
}
What this does is sets up a handler so your form can post the data back to the controller and it will bind your fields on your form to the model parameter.
Once you have done this, you can simply map the model back to EF and persist it to the database.
Also, using a bool is perfectly valid and EF will translate and save it as a 0 or 1 in the database for you.

Resources