MVC How to pass a list of objects with List Items POST action method - asp.net-mvc-3

I want to post a List of items to controller from Razor view , but i am getting a List of objects as null
My class structre is
Model:
List<Subjects> modelItem
class Subjects
{
int SubId{get;set;}
string Name{get;set;}
List<Students> StudentEntires{get;set;}
}
class StudentEntires
{
int StudId{get;set;}
string Name{get;set;}
int Mark{get;set;}
}
The model itself is a list of items and every items contain List of child items as well. Example model is a list of Subjects and every subject contains a List of Students, and i want to input mark for every student
My View is like
#model IList<Subjects>
#{
Layout = "~/Views/Shared/_Layout.cshtml";
}
#using (Html.BeginForm())
{
#Html.ValidationSummary(true)
if (Model.Count > 0)
{
#for (int item = 0; item < Model.Count(); item++)
{
<b>#Model[item].Name</b><br />
#foreach (StudentEntires markItem in Model[item].StudentEntires)
{
#Html.TextBoxFor(modelItem => markItem.Mark)
}
}
<p style="text-align:center">
<input type="submit" class="btn btn-primary" value="Update" />
</p>
}
}
And in controller
[HttpPost]
public ActionResult OptionalMarks(int Id,ICollection<Subjects> model)
{
//BUt my model is null. Any idea about this?
}

You're finding this difficult because you're not utilising the full power of the MVC framework, so allow me to provide a working example.
First up, let's create a view model to encapsulate your view's data requirements:
public class SubjectGradesViewModel
{
public SubjectGradesViewModel()
{
Subjects = new List<Subject>();
}
public List<Subject> Subjects { get; set; }
}
Next, create a class to represent your subject model:
public class Subject
{
public int Id { get; set; }
public string Name { get; set; }
public List<Student> StudentEntries { get; set; }
}
Finally, a class to represent a student:
public class Student
{
public int Id { get; set; }
public string Name { get; set; }
public int Grade { get; set; }
}
At this point, you have all the classes you need to represent your data. Now let's create two controller actions, including some sample data so you can see how this works:
public ActionResult Index()
{
var model = new SubjectGradesViewModel();
// This sample data would normally be fetched
// from your database
var compsci = new Subject
{
Id = 1,
Name = "Computer Science",
StudentEntries = new List<Student>()
{
new Student { Id = 1, Name = "CompSci 1" },
new Student { Id = 2, Name = "CompSci 2" },
}
};
var maths = new Subject
{
Id = 2,
Name = "Mathematics",
StudentEntries = new List<Student>()
{
new Student { Id = 3, Name = "Maths 1" },
new Student { Id = 4, Name = "Maths 2" },
}
};
model.Subjects.Add(compsci);
model.Subjects.Add(maths);
return View(model);
}
[HttpPost]
public ActionResult Index(SubjectGradesViewModel model)
{
if (ModelState.IsValid)
{
return RedirectToAction("Success");
}
// There were validation errors
// so redisplay the form
return View(model);
}
Now it's time to construct the views, and this part is particularly important when it comes to sending data back to a controller. First up is the Index view:
#model SubjectGradesViewModel
#using (Html.BeginForm())
{
#Html.ValidationSummary(true)
#Html.EditorFor(m => m.Subjects) <br />
<input type="submit" />
}
You'll notice I'm simply using Html.EditorFor, whilst passing Subjects as the parameter. The reason I'm doing this is because we're going to create an EditorTemplate to represent a Subject. I'll explain more later on. For now, just know that EditorTemplates and DisplayTemplates are special folder names in MVC, so their names, and locations, are important.
We're actually going to create two templates: one for Subject and one for Student. To do that, follow these steps:
Create an EditorTemplates folder inside your view's current folder (e.g. if your view is Home\Index.cshtml, create the folder Home\EditorTemplates).
Create a strongly-typed view in that directory with the name that matches your model (i.e. in this case you would make two views, which would be called Subject.cshtml and Student.cshtml, respectively (again, the naming is important)).
Subject.cshtml should look like this:
#model Subject
<b>#Model.Name</b><br />
#Html.HiddenFor(m => m.Id)
#Html.HiddenFor(m => m.Name)
#Html.EditorFor(m => m.StudentEntries)
Student.cshtml should look like this:
#model Student
#Html.HiddenFor(m => m.Id)
#Html.HiddenFor(m => m.Name)
#Html.DisplayFor(m => m.Name): #Html.EditorFor(m => m.Grade)
<br />
That's it. If you now build and run this application, putting a breakpoint on the POST index action, you'll see the model is correctly populated.
So, what are EditorTemplates, and their counterparts, DisplayTemplates? They allow you to create reusable portions of views, allowing you to organise your views a little more.
The great thing about them is the templated helpers, that is Html.EditorFor and Html.DisplayFor, are smart enough to know when they're dealing with a template for a collection. That means you no longer have to loop over the items, manually invoking a template each time. You also don't have to perform any null or Count() checking, because the helpers will handle that all for you. You're left with views which are clean and free of logic.
EditorTemplates also generate appropriate names when you want to POST collections to a controller action. That makes model binding to a list much, much simpler than generating those names yourself. There are times where you'd still have to do that, but this is not one of them.

Change the action method signature to
public ActionResult OptionalMarks(ICollection<Subjects> model)
Since in your HTML, it does not look like there is anything named Id in there. This isn't your main issue though.
Next, do the following with the foor loop
#for(int idx = 0; idx < Model[item].StudentEntires.Count();idx++)
{
#Html.TextBoxFor(_ => Model[item].StudentEntries[idx])
}
Possibly due to the use of a foreach loop for the StudentEntries, the model binder is having trouble piecing everything together, and thus a NULL is returned.
EDIT:
Here's an example:
Controller
public class HomeController : Controller
{
public ActionResult Index()
{
var viewModel = new IndexViewModel();
var subjects = new List<Subject>();
var subject1 = new Subject();
subject1.Name = "History";
subject1.StudentEntires.Add(new Student { Mark = 50 });
subjects.Add(subject1);
viewModel.Subjects = subjects;
return View(viewModel);
}
[HttpPost]
public ActionResult Index(IndexViewModel viewModel)
{
return new EmptyResult();
}
}
View
#model SOWorkbench.Controllers.IndexViewModel
#{
ViewBag.Title = "Home Page";
}
#using (Html.BeginForm())
{
#Html.ValidationSummary(true)
if (Model.Subjects.Any())
{
int subjectsCount = Model.Subjects.Count();
for (int item = 0; item < subjectsCount; item++)
{
<b>#Model.Subjects[item].Name</b><br />
int studentEntriesCount = Model.Subjects[item].StudentEntires.Count();
for(int idx = 0;idx < studentEntriesCount;idx++)
{
#Html.TextBoxFor(_ => Model.Subjects[item].StudentEntires[idx].Mark);
}
}
<p style="text-align:center">
<input type="submit" class="btn btn-primary" value="Update" />
</p>
}
}
When you post the form, you should see the data come back in the viewModel object.

Related

MVC3 Persisting data from controller to view back to controller

I have a model containing a couple of lists:
[Display(Name = "Facilities")]
public List<facility> Facilities { get; set; }
[Display(Name = "Accreditations")]
public List<accreditation> Accreditations { get; set; }
I populate these lists initially from my controller:
public ActionResult Register()
{
var viewModel = new RegisterModel();
viewModel.Facilities = m_DBModel.facilities.ToList();
viewModel.Accreditations = m_DBModel.accreditations.ToList();
return View(viewModel);
}
When they get to my view they are populated with the DB records (great). I then pass the model to the partial view which displays these lists as checkboxes, ready for user manipulation (I have tried based on another suggestion using for loop instead of foreach loop, made no difference):
#model LanguageSchoolsUK.Models.RegisterModel
#foreach (var item in Model.Facilities)
{
#Html.Label(item.name);
#Html.CheckBox(item.name, false, new { id = item.facility_id, #class = "RightSpacing", #description = item.description })
}
When I submit the form and it ends up back at my controller this time calling the overloaded register function on the controller:
[HttpPost]
public ActionResult Register(RegisterModel model)
{
if (ModelState.IsValid)
{
// Do stuff
}
return View(model);
}
The problem is that the model parameter containing the lists (Facilities and Accreditations) is telling me that the lists are null.
Please can somebody tell me what I am doing wrong, why aren't they populated with the collections that I originally passed through and hopefully a way of asking whick ones have been checked?
Thanks.
I have tried based on another suggestion using for loop instead of
foreach loop, made no difference
Try again, I am sure you will have more luck this time. Oh and use strongly typed helpers:
#model LanguageSchoolsUK.Models.RegisterModel
#for (var i = 0; i < Model.Facilities.Count; i++)
{
#Html.HiddenFor(x => x.Facilities[i].name)
#Html.LabelFor(x => x.Facilities[i].IsChecked, Model.Facilities[i].name);
#Html.CheckBoxFor(
x => x.Facilities[i].IsChecked,
new {
id = item.facility_id,
#class = "RightSpacing",
description = item.description // <!-- HUH, description attribute????
}
)
}
Also you will undoubtedly notice from my answer that checkboxes work with boolean fields on your model, not integers, not decimals, not strings => BOOLEANS.
So make sure that you have a boolean field on your model which will hold the state of the checkbox. In my example this field is called IsChecked but obviously you could feel absolutely free to find it a better name.

Why is {System.Web.Mvc.SelectList} DropDownList SelectedValue

I have created a DropDownList, as described in my last question here
I have been trying to figure out how to get the selected value of the list. I used the answer that was provided but the only thing it returned was {System.Web.Mvc.SelectList}
I debugged it and sure enough the string that was in the "Value" column was {System.Web.Mvc.SelectList}
What am I doing wrong here? I have been miserably failing at MVC and am new at it.
Thank you for the help
Your Action in your controller should look like this:
[HttpPost]
public ActionResult Index(int DropOrgId)
{
System.Diagnostics.Debugger.Break();
return null;
}
The important thing to note is that "DropOrgId" is the same as the string name you passed into #Html.DropDownList("DropOrgID") in your view. This name will store the value of the input from the HTML input control, in this case the
The source will be:
<select id="DropOrgID" name="DropOrgID">...</select>
The id of the input control is how the MVC framework will match up the value of that control to the parameter of the action you are looking for.
Here is a sample app that shows it:
Class
public class Organization
{
public int OrganizationID { get; set; }
public string Name { get; set; }
}
Controller
public class HomeController : Controller
{
public ActionResult Index()
{
var orgs = new List<Organization>();
foreach (var count in Enumerable.Range(1, 10))
{
var newOrg = new Organization();
newOrg.OrganizationID = count;
newOrg.Name = "Organization " + count.ToString();
orgs.Add(newOrg);
}
ViewBag.DropOrgID = new SelectList(orgs, "OrganizationID", "Name", 3);
return View();
}
[HttpPost]
public ActionResult Index(int DropOrgID)
{
//You can check that this DropOrgID contains the newly selected value.
System.Diagnostics.Debugger.Break();
return null;
}
}
Index View
<h2>Index</h2>
#using (Html.BeginForm())
{
#Html.DropDownList("DropOrgID")
<br />
<br />
<input type="submit" value="Save" />
}

Add to model in form, then redisplay form to add more

I'm new to MVC3, but so far I have managed to get along with my code just great.
Now, I would like to make a simple form, that allows the user to input a text string, representing the name of an employee. I would then like this form to be submitted and stored in my model, in a sort of list. The form should then re-display, with a for-each loop writing out my already added names. When I'm done and moving on, I need to store this information to my database.
What I can't figure out, is how to store this temporary information, until i push it to my database. Pushing everytime I submit I can do, but this has cause me alot of headaches.
Hope you guys see what I'm trying to do, and have an awesome solution for it. :)
This is a simplified version of what I've been trying to do:
Model
public class OrderModel
{
public virtual ICollection<Employees> EmployeesList { get; set; }
public virtual Employees Employees { get; set; }
}
public class Employees
{
[Key]
public int ID { get; set; }
public string Name { get; set; }
}
View
#model OrderModel
#{
if (Model.EmployeesList != null)
{
foreach (var c in Model.EmployeesList)
{
#c.Name<br />
}
}
}
#using(Html.BeginForm())
{
#Html.TextBoxFor(m => m.Employees.Name)
<input type="submit" value="Add"/>
}
Controller
[HttpPost]
public ActionResult Index(OrderModel model)
{
model.EmployeesList.Add(model.Employees);
// This line gives me the error: "System.NullReferenceException: Object reference not set to an instance of an object."
return View(model);
}
I think you should handle this by burning the employee list into the page. Right now, you're not giving your form any way of recognizing the list.
In an EditorTemplates file named Employees:
#model Employees
#Html.HiddenFor(m => m.ID)
#Html.HiddenFor(m => m.Name);
In your view:
#using(Html.BeginForm())
{
#Html.EditorFor(m => m.EmployeesList)
#Html.TextBoxFor(m => m.Employees.Name)
<input type="submit" value="Add"/>
}
[HttpPost]
public ActionResult Index(OrderModel model)
{
if (model.EmployeesList == null)
model.EmployeesList = new List<Employees>();
model.EmployeesList.Add(model.Employees);
return View(model);
}
As an added bonus to this method, it would be easy to add ajax so the user never has to leave the page when they add new employees (You might be able to just insert a new hidden value with javascript and avoid ajax. It would depend on if you do anything other than add to your list in your post).
I think this would be a good use for TempData. You can store anything in there, kind of like the cache, but unlike the cache it only lasts until the next request. To implement this, change the action method like this (example only):
[HttpPost]
public ActionResult Index(OrderModel model)
{
dynamic existingItems = TempData["existing"];
if (existingItems != null)
{
foreach (Employee empl in existingItems)
model.EmployeesList.Add(empl );
}
model.EmployeesList.Add(model.Employees);
TempData["existing"] = model.EmployeesList;
return View(model);
}

Sending data from hardcoded dropdwonlist to controller

Migrating from textboxe to dropdownlist – Need to send value from a hard-coded dropdownlist to controller
The code below is used in the controller
var list = new SelectList(new[]
{
new{ID="1",Name="20012"},
new{ID="2",Name="20011"},
new{ID="3",Name="20010"},
new {ID="4",Name="2009"},
new{ID="5",Name="2008"},
new{ID="6",Name="2007"},
new{ID="7",Name="2006"},
new{ID="8",Name="2005"},
new{ID="9",Name="2004"},
new{ID="3",Name="2003"},
new{ID="3",Name="2002"},
new{ID="3",Name="2001"},
new{ID="3",Name="2000"},
},
"ID", "Name", 1);
ViewData["list"] = listYear;
The code below is used in the view
#using (Html.BeginForm()){
<p>
Title: #Html.TextBox("SearchString")
#Html.DropDownList("list",ViewData["list"] as SelectList)
Genre: #Html.DropDownList("Towns", "All")
<input type="submit" value="Filter" /></p>
}
Below is the code which was used for the textbox
if (!String.IsNullOrEmpty(year))
{
car = Cars.Where(s => s.Year.Contains(year));
}
Looks like you are trying to select a value from a selectlist and send that value to the controller. First off, I'd suggest you use a ViewModel instead of magic strings. You should modify your View to accept the new ViewModel and then post the model to your action. It's easy, cleaner and more maintainable.
Here is what your model would look like
public class VehicleYearsViewModel {
public SelectList VehicleYears { get; set; }
public int SelectedYear { get; set; }
public VehicleYearsViewModel() {
VehicleYears = new SelectList(new[]
{
new{ID="1",Name="2012"},
new{ID="2",Name="2011"},
new{ID="3",Name="2010"},
new{ID="4",Name="2009"},
new{ID="5",Name="2008"},
new{ID="6",Name="2007"},
new{ID="7",Name="2006"},
new{ID="8",Name="2005"},
new{ID="9",Name="2004"},
new{ID="3",Name="2003"},
new{ID="3",Name="2002"},
new{ID="3",Name="2001"},
new{ID="3",Name="2000"}
}
}
}
Your View then would look like so:
#YourAppName.Models.VehicleYearsViewModel
#using (Html.BeginForm()){
#Html.ValidationSummary(true)
#Html.DropDownListFor(model => model.SelectedYear, Model.VehicleYears, "ID", "Name", 1))
<input type="submit" value="OK" />
}
Your controller action would accept the model and can make use of the selected value as an int datatype.
I'm just guessing since your controller action isn't posted but this is pretty much what it would look like:
public class HomeController : Controller {
public ActionResult Index() {
var model = new VehicleYearsViewModel();
return View(model);
}
[HttpPost]
public ActionResult Index(VehicleYearsViewModel model) {
if(ModelState.IsValid) {
// you can get selected year like so
int selectedYear = model.SelectedYear;
// ... your code here to do whatever with selectedYear
}
return View(model);
}
}
Hope this helps

MVC-3 DropdownList or DropdownListFor - Can't save values in controller POST

I searches for hours (or days) and didn't find a solution yet. I want to edit a customer with a DropdownListFor for the salutation with the right preselected value.
I've got 3 entities (Database first concept, this is not my own design...): customer, address, salutation
A CUSTOMER has an address_id (f_key) and an ADDRESS has got a salutation_id (f_key). The ADDRESS holds the first and last name for example. Inside the SALUTATION entity there is a column sal1 which holds all possible salutations.
Now, I want to edit my customer via a ViewModel which looks like this:
public class CustomerViewModel
{
public CUSTOMER cust { get; set; }
public SelectList salutationList { get; set; }
CustomerRepository repository = new CustomerRepository();
public CustomerViewModel(int id)
{
cust = repository.GetCustomerByIdAsQueryable(id).Single();
salutationList = new SelectList(repository.GetSalutations(), cust.ADDRESS.SALUTATION.SAL1);
}
// Some more
}
The CutsomerRepository methods:
public class CustomerRepository
{
private MyEntities db = new MyEntities();
public IQueryable<CUSTOMER> GetCustomerByIdAsQueryable(int id) {...}
public IQueryable<CUSTOMER> GetCustomersByName(string firstName, string lastName, int maxCount) {...}
public List<string> GetSalutations()
{
var salutationList = new List<string>();
var salutationListQry = from s in db.SALUTATION
select s.SAL1;
salutationListTemp.AddRange(salutationListQry);
return salutationList;
}
// ...
}
This is my controller method:
[HttpPost]
public ActionResult CustomerData(int id, FormCollection fc)
{
var vm = new CustomerViewModel(id);
// Why do I need the following line?
vm.cust = repository.GetCustomerByIdAsQueryable(id).Single();
try
{
UpdateModel(vm, fc);
repository.Save();
return View("CustomerData", vm);
}
catch (Exception e)
{
return View();
}
}
And finally the part from my View:
#model WebCRM.ViewModels.CustomerViewModel
#using (Html.BeginForm())
{
// ...
<div class="editor-label">
#Html.Label("Salutation:")
#Html.DropDownListFor(model => model.cust.ADDRESS.SALUTATION.SAL1, Model.salutationList)
// #Html.DropDownList("Salutation", Model.salutationList)
</div>
<div class="editor-label">
</div>
<div class="editor-field">
#Html.Label("Last name:")
#Html.EditorFor(model => model.cust.ADDRESS.LASTNAME)
#Html.ValidationMessageFor(model => model.cust.ADDRESS.LASTNAME)
</div>
<p>
<input type="submit" value="Speichern" />
</p>
}
Changing and saving last names works fine. But when saving the salutation it changes the SAL1 value in the SALUTATION entity to the one I've chosen in the DropdownListFor. What I want is to change the salutation_id inside the ADDRESS entity for my customer. Why isn't that working?
Another strange behavoior: When removing the marked line in my CustomerController, I can't even change and save the last name. Normally the constructor of the CustimerViewModel sets the customer. So why do I have to have the line of code for setting the customer inside my ViewModel? It's duplicated, but has to be there...
Thanks in advance.
You need to have Selected property in your list.
I can show you my working example:
public static IEnumerable<SelectListItem> GetCountries(short? selectedValue)
{
List<SelectListItem> _countries = new List<SelectListItem>();
_countries.Add(new SelectListItem() { Text = "Select country...", Value = "0", Selected = selectedValue == 0 });
foreach (var country in ObjectFactory.GetInstance<DataRepository>().GetCountries())
{
_countries.Add(new SelectListItem()
{
Text = country.Name,
Value = country.ID.ToString(),
Selected = selectedValue > 0 && selectedValue.Equals(country.ID)
});
}
return _countries;
}
In controller i store this into viewbag:
ViewBag.Countries = CompanyModel.GetCountries(0);
In view:
#Html.DropDownListFor(m => m.CompanyModel.CountryId, (IEnumerable<SelectListItem>)ViewBag.Countries)

Resources