ASP NET MVC 4 collection is null on post - c#

I read most of Google :-), but I can't proceed. The collection on my object is and stays null on post, whatever I do.
My Model:
public class ArticleViewModel
{
public Guid EventId { get; set; }
public IList<ArticleItemViewModel> ArtikelListe { get; set; }
public decimal GesamtpreisNetto { get; set; }
public decimal MwSt { get; set; }
}
and
public class ArticleItemViewModel
{
public Guid EventId { get; set; }
public Guid Id { get; set; }
public string Artikelname { get; set; }
public string Artikelname_EN { get; set; }
public string Information { get; set; }
public string Information_EN { get; set; }
public decimal Preis { get; set; }
public bool MitAnzahl { get; set; }
public bool IstKategorie { get; set; }
public int Anzahl { get; set; }
public bool Checkbox { get; set; }
public int Reihenfolge { get; set; }
}
My View:
#using (Html.BeginForm("Next", "Article", FormMethod.Post))
{
#Html.HiddenFor(x => x.EventId)
<input type="hidden" name="ArtikelListe" />
for (var i = 0; i < Model.ArtikelListe.Count; i++)
// foreach (EventManager.ViewModels.ArticleItemViewModel artikelItem in Model.ArtikelListe)
{
<div>
<div>
#if (Model.ArtikelListe[i].IstKategorie)
{
#Html.LabelFor(x => x.ArtikelListe[i].Artikelname)<br />
#Html.LabelFor(x => x.ArtikelListe[i].Information)
}
else
{
if (Model.ArtikelListe[i].MitAnzahl)
{
#Html.TextBoxFor(x => x.ArtikelListe[i].Anzahl, new { #class = "field text fn" })
}
else
{
#Html.LabelFor(x => x.ArtikelListe[i].Anzahl)
}
#Html.LabelFor(x => x.ArtikelListe[i].Artikelname)<br />
#Html.LabelFor(x => x.ArtikelListe[i].Information)
}
</div>
</div>
}
On post, I get my Viewmodel back and it has a Collection of ArtikelListe with 15 items (thats correct), but these are all null!
In my HTTP Header I get the following post data:
EventId:824e7f3c-7190-4ebb-aa60-51b57c977b1e
ArtikelListe:
ArtikelListe[1].Anzahl:0
ArtikelListe[2].Anzahl:1
ArtikelListe[3].Anzahl:0
submitButton:Nächste
I wonder why just partial data is sent withon the http post and why all my list items are null. I tried to render by for and foreach. same result.
Any ideas? I'm helpless.

Collection indexers must start at zero and be consecutive (unless you include an Index property).Because of your if statements, you are not necessarily generating a control for the property Anzahl. Looking at your header information, you do not have a value for ArtikelListe[0].Anzahl which means that the first item must have either IstKategorie=true or MitAnzahl=false. You can correct this by adding a hidden input so a value posts back
#if (Model.ArtikelListe[i].IstKategorie)
{
#Html.LabelFor(x => x.ArtikelListe[i].Artikelname)<br />
#Html.LabelFor(x => x.ArtikelListe[i].Information)
#Html.HiddenFor(x => x.ArtikelListe[i].Anzahl) // add this
}
else
{
if (Model.ArtikelListe[i].MitAnzahl)
{
#Html.TextBoxFor(x => x.ArtikelListe[i].Anzahl, new { #class = "field text fn" })
}
else
{
#Html.LabelFor(x => x.ArtikelListe[i].Anzahl)
#Html.HiddenFor(x => x.ArtikelListe[i].Anzahl) // add this
}
#Html.LabelFor(x => x.ArtikelListe[i].Artikelname)<br />
#Html.LabelFor(x => x.ArtikelListe[i].Information)
}
Alternatively you can add an Index property which the DefaultModelBinder uses to match up collection items that are non-consecutive
#if (Model.ArtikelListe[i].IstKategorie)
{
#Html.LabelFor(x => x.ArtikelListe[i].Artikelname)<br />
#Html.LabelFor(x => x.ArtikelListe[i].Information)
}
else
{
if (Model.ArtikelListe[i].MitAnzahl)
{
#Html.TextBoxFor(x => x.ArtikelListe[i].Anzahl, new { #class = "field text fn" })
<input type="hidden" name="x.ArtikelListe.Index" value="#i" /> // add this manually
}
else
{
#Html.LabelFor(x => x.ArtikelListe[i].Anzahl)
}
#Html.LabelFor(x => x.ArtikelListe[i].Artikelname)<br />
#Html.LabelFor(x => x.ArtikelListe[i].Information)
}
With the first option, it will post back all items. In the second case it will post back only items that meet the if conditions.
Note as Sergey noted, you need to also remove <input type="hidden" name="ArtikelListe" />

The issue in this line:
<input type="hidden" name="ArtikelListe" />
When POST request is sent back:
ArtikelListe:
ArtikelListe[1].Anzahl:0
ArtikelListe[2].Anzahl:1
ArtikelListe[3].Anzahl:0
Then ArtikelListe overrides value for the list and that's why it's always null.
So you just need to rename your hidden field to some another name to not conflict with existing names.
Here is working example based on your MVC code in DotNetFiddle - https://dotnetfiddle.net/BCXduq
You can click RUN, then enter some values in two input fields in the right bottom box, and click Save button. And then it will display model that server received in POST as JSON text.

Thank you guys.
The problem was, that I did the testing with the script from the Fiddle. In this code
Model.ArtikelListe[i].MitAnzahl
was always true.
In case it is not true, the value "Anzahl" was not bound to a control containing a value (but just a label).
#Html.LabelFor(x => x.ArtikelListe[i].Anzahl)
As soon as I inserted a hidden field within that scope and bound the "Anzahl" value to it, the post returned with all the data I expected.
Thanks anyway. I learned a lot!

Related

Collection in ViewModel gone after postback

I have the following ViewModel:
public class ActivityReportViewModel
{
public Dictionary<int, List<string>> Periods { get; set; }
public List<Project> Projects { get; set; }
public List<Templates> Templates { get; set; }
public DateTime TimePeriod { get; set; }
}
public class Project
{
public string Customer { get; set; }
public string ProjectNumber { get; set; }
public string ProjectDescription { get; set; }
public bool IsSelected { get; set; }
public int TemplateId { get; set; }
public bool XLSX { get; set; }
public bool PDF { get; set; }
}
I fill this ViewModel in my controller and then send it to my Create view, which works fine and the values of the Projects property are all there. However, when I postback the data to the server, the values are gone. I tried supplying HiddenFields to all properties of each Project to no avail. Here's my relevant view markup:
<div>
#Html.LabelFor(model => model.Projects, htmlAttributes: new { #class = "ms-Label" })
<ul class="ms-List" style="list-style:none;">
#for (int x = 0; x < Model.Projects.Count; x++)
{
<li class="ms-ListItem">
<span class="ms-ListItem-primaryText">#Model.Projects[x].ProjectDescription</span>
<span class="ms-ListItem-secondaryText">#Model.Projects[x].Customer</span>
<span class="ms-ListItem-tertiaryText">#Model.Projects[x].ProjectNumber</span>
#*<div class="ms-ListItem-selectionTarget js-toggleSelection"></div>*#
#Html.HiddenFor(m => Model.Projects[x].IsSelected)
#Html.HiddenFor(m => Model.Projects[x].ProjectDescription)
#Html.HiddenFor(m => Model.Projects[x].Customer)
#Html.HiddenFor(m => Model.Projects[x].ProjectNumber)
#Html.HiddenFor(m => Model.Projects[x].XLSX)
#Html.HiddenFor(m => Model.Projects[x].PDF)
<div class="ms-Dropdown">
<i class="ms-Dropdown-caretDown ms-Icon ms-Icon--caretDown"></i>
#Html.DropDownListFor(m => m.Projects[x].TemplateId, new SelectList(Model.Templates, "Id", "Name"), new { #class = "ms-Dropdown-select" })
</div>
<div class="ms-ChoiceField">
<input id="excel+#Model.Projects[x].ProjectNumber" class="ms-ChoiceField-input" value="#Model.Projects[x].XLSX" type="checkbox">
<label for="excel+#Model.Projects[x].ProjectNumber" class="ms-ChoiceField-field"><span class="ms-Label is-required">Excel</span></label>
</div>
<div class="ms-ChoiceField">
<input id="pdf+#Model.Projects[x].ProjectNumber" class="ms-ChoiceField-input" value="#Model.Projects[x].PDF" type="checkbox">
<label for="pdf+#Model.Projects[x].ProjectNumber" class="ms-ChoiceField-field"><span class="ms-Label is-required">PDF</span></label>
</div>
</li>
}
</ul>
<div>
#Html.ValidationMessageFor(model => model.Projects, "", new { #class = "text-danger" })
</div>
</div>
EDIT:
Here's my POST action method:
[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult Create(ActivityReportViewModel report)
{
using (AppContainer _db = new AppContainer())
{
if (ModelState.IsValid)
{
_db.SaveChanges();
return RedirectToAction("Index");
}
return PartialView(report);
}
}
The DefaultViewModel Binder uses the HTML attribute name to determine which property to bind back to on the server. I cannot see name attribute specified on your input element. Please specify name attribute on the elements you wish to post back to the server with the property of the view model.
Specifiy name attribute as below. Notice I have added name attribute with value as the property of your view model
<input id="excel+#Model.Projects[x].ProjectNumber" class="ms-ChoiceField-input" name="#Model.Projects[x].ProjectNumber" value="#Model.Projects[x].XLSX" type="checkbox">

View not passing Ienumerable of Model

Edit: Removed Partial View to make things simpler. Now I just need to find out why The View isn't Posting the Values
ViewModelProspectUsers
public class ViewModelProspectUsers
{
public int Id { get; set; }
public string User { get; set; }
public IEnumerable<ViewModelProspectSelect> Prospects { get; set; }
}
ViewModelProspectSelect
public class ViewModelProspectSelect
{
public int ProspectID { get; set; }
public string Name { get; set; }
public bool IsSelected { get; set; }
}
View
#model OG.ModelView.ViewModelProspectUsers
#using (Html.BeginForm())
{
#Html.HiddenFor(model => model.Id)
<h5>Please Select Prospects you wish to assign to this User.</h5>
-----HERE is where the partial used to be, these values aren't being posted to the [Post] Method------
-----------------------------------------However they are populating just fine----------------------------------------
#foreach (var item in Model.Prospects)
{
#Html.HiddenFor(x => item.ProspectID)
#Html.DisplayFor(x => item.Name)
#Html.EditorFor(x => item.IsSelected)
}
#*#Html.Partial("_ShowProspectCheckedForUser", Model.Prospects)*#
#*#Html.Partial("_ShowProspectCheckedForuser", new OG.ModelView.ViewModelProspectSelect())*#
<input type="submit" value="Save changes" />
#Html.ActionLink("Cancel", "Index")
}
Post
[HttpPost]
public ActionResult UsersInProspect(ViewModelProspectUsers viewModel)
If i were to look at viewModel.Prospects(m=>m.isSelected) //<- this value is Null shouldn't be
My viewmodel Variableis showing Data but not for the Ienumerable.
When dealing with list-type objects, you must reference them with array notation to have the field names generated in a way that the modelbinder can parse them back, i.e:
for (var i = 0; i < Model.Count(); i++)
{
#Html.LabelFor(m => Model[i].SomeProperty)
#Html.EditorFor(m => Model[i].SomeProperty)
}
In your scenario, you'd be better served by using a view model to contain your list and adding a Selected property to the items so that you can track which ones were or were not selected.
public class ViewModelProspects
{
public List<ViewModelProspectSelect> Prospects { get; set; }
}
public class ViewModelProspectSelect
{
// Whatever else you have
public bool Selected { get; set; }
}
Then, in your view:
#model ViewModelProspects
#using (Html.BeginForm())
{
for (var i = 0; i < Model.Prospects.Count(); i++)
{
<label>
#Html.HiddenFor(m => Model.Prospects[i].Id)
#Html.CheckboxFor(m => Model.Prospects[i].Selected, true)
#Model.Prospects[i].Name
</label>
}
}
And finally, change your action method signature:
[HttpPost]
public ActionResult UsersInProspect(ViewModelProspects model)
Then, you can easily get the list of selected ids inside the action with:
var selectedIds = model.Prospects.Where(m => m.Selected).Select(m => m.Id)

MVC editorfor not working for collection

I have a model class called Events and a model class called EventRange:
public class Event
{
public int Id { get; set; }
public string Name { get; set; }
public string Description { get; set; }
public List<EventRange> RangesCollection { get; set; }
}
public class EventRange
{
public int Id { get; set; }
public string RangeName { get; set; }
public string RangeDescription { get; set; }
public int Capacitiy { get; set; }
}
As you can see the Event class contains a List for as many EventRanges as the user should be able to add a lot of EventRanges.
I have created a view called events, which dynamicly appends a partial view for the evenrange. The user can in example press the Add Event Range button 5 times if he want's 5 EventRanges saved.
The Event view:
#using (Ajax.BeginForm("CreateEvent", "Events", new AjaxOptions { HttpMethod = "POST" }, new { #class = "mainForm" }))
{
#*Event data:*#
#Html.LabelFor(m => m.Name)#Html.TextBoxFor(m => m.Name)
#Html.LabelFor(m => m.Description)#Html.TextBoxFor(m => m.Description)
#*EventRange data:*#
<div id="EventRangediv">
#Html.EditorFor(m => m.RangesCollection)
</div>
}
The partial view for the eventrange is saved under "~/views/events/EditorTemplates/EventRange.cshtml"
EventRange.cshtml:
#model fanaticksMain.Models.EventRange
#Html.HiddenFor(m => m.Id)
#Html.DisplayFor(m => m.RangeName)
#Html.LabelFor(m => m.RangeName)#Html.TextBoxFor(m => m.RangeName)
#Html.LabelFor(m => m.RangeDescription)#Html.TextBoxFor(m => m.RangeDescription)
However, loading the events view doesn't load any element from the partialview, the labels and textboxes for the name and description for the event work. But nothing is shown for the eventrange partial view.
Anyone have anyone idea what I'm doing wrong? Also, does anyone have any suggestion if this is the right way to bind a collection for posting a form?
EventRange.cshtml has the model specified as EventRange. m.RangesCollection is a collection of EventRange objects.
I don't see a model that is defined as accepting a collection of EventRange.
try place a for loop in your code to iterate each EventRange and display the EventRange.cshtml editor for each one:
Instead of:
#Html.EditorFor(m => m.RangesCollection)
Try:
#for (int i = 0; i < m.RangeCollection.Count; i++)
{
#Html.EditorFor(m => m.RangeCollection[i])
}
Try placing the "EventRange.cshtml" in the “~/Views/Shared/EditorTemplates/” folder.

.net mvc4 HttpPost null value

I have a problem while passing an object with HttpPost...
Once the form is submitted, the model is set "null" on the controller side, and I don't know where is the issue..
Here is my controller :
public ActionResult AddUser(int id = 0)
{
Group group = db.Groups.Find(id);
List<User> finalList = db.Users.ToList() ;
return View(new AddUserTemplate()
{
group = group,
users = finalList
});
//Everything is fine here, the object is greatly submitted to the view
}
[HttpPost]
public ActionResult AddUser(AddUserTemplate addusertemplate)
{
//Everytime we get in, "addusertemplate" is NULL
if (ModelState.IsValid)
{
//the model is null
}
return View(addusertemplate);
}
Here is AddUserTemplate.cs :
public class AddUserTemplate
{
public Group group { get; set; }
public User selectedUser { get; set; }
public ICollection<User> users { get; set; }
}
Here is the form which return a null value to the controller (note that the dropdown list is greatly populated with the good values) :
#using (Html.BeginForm()) {
<fieldset>
<legend>Add an user</legend>
#Html.HiddenFor(model => model.group)
#Html.HiddenFor(model => model.users)
<div class="editor-field">
//Here, we select an user from Model.users list
#Html.DropDownListFor(model => model.selectedUser, new SelectList(Model.users))
</div>
<p>
<input type="submit" value="Add" />
</p>
</fieldset>
}
Thanks a lot for your help
I tried your code and in my case the addusertemplate model was not null, but its properties were all null.
That's because of a few model binding issues: Html.HiddenFor and Html.DropDownListFor do not work with complex types (such as Group or User) (at least that's how it is by default).
Also, Html.HiddenFor cannot handle collections.
Here's how to solve these issues:
instead of #Html.HiddenFor(model => model.group) there should be one #Html.HiddenFor for each property of the group that you need bound
instead of #Html.HiddenFor(model => model.users) you need to iterate through the list of users and for each object add #Html.HiddenFor for each property of the user that you need bound
instead of #Html.DropDownListFor(model => model.selectedUser [...], create a property like int SelectedUserId {get;set;} and use that in the DropDownList (as it cannot handle complex types).
Here's the code that works:
1. The User and Group classes, as I imagined them to be:
public class User
{
public int Id { get; set; }
public string Name { get; set; }
}
public class Group
{
public int Id { get; set; }
public string Name { get; set; }
}
2. The adjusted AddUserTemplate class:
public class AddUserTemplate
{
public Group Group { get; set; }
public IList<User> Users { get; set; }
public int SelectedUserId { get; set; }
public User SelectedUser
{
get { return Users.Single(u => u.Id == SelectedUserId); }
}
}
The adjustments:
Users was changed from ICollection to IList, because we'll need to access elements by their indexes (see the view code)
added SelectedUserId property, that will be used in the DropDownList
the SelectedUser is not a readonly property, that returns the currently selected User.
3. The adjusted code for the view:
#using (Html.BeginForm())
{
<fieldset>
<legend>Add an user</legend>
#*Hidden elements for the group object*#
#Html.HiddenFor(model => model.Group.Id)
#Html.HiddenFor(model => model.Group.Name)
#*Hidden elements for each user object in the users IList*#
#for (var i = 0; i < Model.Users.Count; i++)
{
#Html.HiddenFor(m => m.Users[i].Id)
#Html.HiddenFor(m => m.Users[i].Name)
}
<div class="editor-field">
#*Here, we select an user from Model.users list*#
#Html.DropDownListFor(model => model.SelectedUserId, new SelectList(Model.Users, "Id", "Name"))
</div>
<p>
<input type="submit" value="Add" />
</p>
</fieldset>
}
Another option that does not require a bunch of hidden fields is to simply specify that you want the model passed to the controller. I think this is much cleaner.
#using(Html. BeginForm("action","controller", Model, FormMethod.Post)){
...
}

How to get subcollections on viewmodel on postback in MVC3?

Phil Haack has an article that describes how to set things up so the default model binder will bind to a collection on a post back:
http://haacked.com/archive/2008/10/23/model-binding-to-a-list.aspx
The problem I am having is I am not just trying to send a collection back to the Controller action, but a ViewModel with a collection.
I have a class that basically looks like this:
public class MyViewModel
{
public int IncidentNumber { get; set; }
public string StoreId { get; set; }
public string RepId { get; set; }
public string OrderStatus { get; set; }
public CustomerViewModel Customer { get; set;
//... other properties and SelectLists for binding
public IEnumerable<OrderItemViewModel> OrderItemViewModels { get; set; }
I can actually get the CustomerViewModel data back on a postback, but the list of OrderItemViewModels is empty. How do I get those back? Phil's article isn't helping there.
I had a similar problem here MVC binding to model with list property ignores other properties which was solved by using the following code within the view
<div class="editor-field">
#for (int i = 0; i < Model.MyCollection.Count(); i++)
{
#Html.HiddenFor(m => m.MyCollection[i].Id)
#Html.HiddenFor(m => m.MyCollection[i].ParentId)
#Html.HiddenFor(m => m.MyCollection[i].Name)
#Html.TextBoxFor(m => m.MyCollection[i].Value)
}
</div>
Use an editor template:
#model MyViewModel
#using (Html.BeginForm())
{
... some input fields
#Html.EditorFor(x => x.OrderItemViewModels)
<input type="submit" value="OK" />
}
and then inside the corresponding editor template which will automatically be rendered for each element of the OrderItemViewModels collection (~/Views/Shared/EditorTemplates/OrderItemViewModels.cshtml):
#model OrderItemViewModels
<div>
#Html.LabelFor(x => x.Prop1)
#Html.EditorForFor(x => x.Prop1)
</div>
<div>
#Html.LabelFor(x => x.Prop2)
#Html.EditorForFor(x => x.Prop2)
</div>
...

Categories