ViewModel for multiple file upload in ASP.NET MVC 3 - asp.net-mvc-3

I have multiple file upload Views with ViewModel binding as following:
#model IVRControlPanel.Models.UploadNewsModel
#using (Html.BeginForm("index", "NewsUpload", FormMethod.Post, new { name = "form1", #id = "form1" }))
{
#Html.ValidationSummary(true)
<div class="field fullwidth">
<label for="text-input-normal">
#Html.Label("Select Active Date Time")</label>
<input type="text" id="active" value="#DateTime.Now" />
#Html.ValidationMessageFor(model => model.ActiveDateTime)
</div>
<div class="field fullwidth">
<label>
#Html.Label("Select Language")
</label>
#Html.DropDownList("Language", (SelectList)ViewBag.lang)
</div>
<div class="field">
<label>
#Html.Label("General News")
</label>
#Html.TextBoxFor(model => model.generalnews, new { name = "files", #class="custom-file-input", type = "file" })
#Html.ValidationMessageFor(model => model.generalnews)
</div>
<div class="field">
<label>
#Html.Label("Sports News")
</label>
#Html.TextBoxFor(model => model.sportsnews, new { name = "files", #class = "custom-file-input", type = "file" })
#Html.ValidationMessageFor(model => model.sportsnews)
</div>
<div class="field">
<label>
#Html.Label("Business News")
</label>
#Html.TextBoxFor(model => model.businessnews, new { name = "files", #class = "custom-file-input", type = "file" })
#Html.ValidationMessageFor(model => model.businessnews)
</div>
<div class="field">
<label>
#Html.Label("International News")
</label>
#Html.TextBoxFor(model => model.internationalnews, new { name = "files", #class = "custom-file-input", type = "file" })
#Html.ValidationMessageFor(model => model.internationalnews)
</div>
<div class="field">
<label>
#Html.Label("Entertaintment News")
</label>
#Html.TextBoxFor(model => model.entertaintmentnews, new { name = "files", #class = "custom-file-input", type = "file" })
#Html.ValidationMessageFor(model => model.entertaintmentnews)
</div>
<footer class="pane">
<input type="submit" class="bt blue" value="Submit" />
</footer>
}
View model with data annotation for validating file upload for allowed extension as follows:
public class UploadNewsModel
{
public DateTime ActiveDateTime { get; set; }
// public IEnumerable<SelectListItem> Language { get; set; }
[File(AllowedFileExtensions = new string[] { ".jpg", ".gif", ".tiff", ".png", ".pdf", ".wav" }, MaxContentLength = 1024 * 1024 * 8, ErrorMessage = "Invalid File")]
public HttpPostedFileBase files { get; set; }
}
Controller: for saving multiple file and return view if error is exist
[HttpPost]
public ActionResult Index(UploadNewsModel news, IEnumerable<HttpPostedFileBase> files)
{
if (ModelState.IsValid)
{
foreach (var file in files)
{
if (file != null && file.ContentLength > 0)
{
var fileName = Path.GetFileName(file.FileName);
var serverpath = Server.MapPath("~/App_Data/uploads/News");
var path = Path.Combine(serverpath, fileName);
if (!Directory.Exists(serverpath))
{
Directory.CreateDirectory(serverpath);
}
file.SaveAs(path);
}
}
}
return View(news);
}
}
Problem explaination
How do I define view model for those five file upload input control so that corresponding error is shown for respective validation error if file extension of file uploaded is not allowed type. I have only one view model items for all five file upload control.
What can be best way to define view model for those multiple file upload control for showing respective validation error instead user try to upload file of unallowed extension???

The real problem here is that MVC doesn't have a decent model binder for http files.
So unless you use a project like mvc futures which has some extra support around file uploads you are going to have to get some what dirty and do the hard work yourself.
Here is an example that might work a bit better for you.
Firstly I would create a ViewModel to represent one file something like this:
public class FileViewModel
{
public Guid Id { get; set; }
public string Name { get; set; }
public bool Delete { get; set; }
public string ExistingUrl { get; set; }
public HttpPostedFileBase FileBase { get; set; }
}
Obviously properties depend on your requirements, the important bit is the FileBase and that it is its own model.
Next, a ViewModel for your page (UploadNewsModel in your case):
public class IndexViewModel
{
public IList<FileViewModel> Files { get; set; }
}
The important bit here is the IList of Files, this is how we capture multiple files (in your current implementation with 'file' you are only capturing one.
Onto the page level view:
#model IndexViewModel
<form method="post" action="#Url.Action("Index")" enctype="multipart/form-data">
#Html.ValidationSummary(true)
#Html.EditorFor(x => x.Files)
<input type="submit" value="Submit" />
</form>
Note the EditorFor, what we will do next is create a EditorTemplate for the FileViewModel which should be used at this point.
Like this:
#model FileViewModel
<h4>#Model.Name</h4>
#Html.HiddenFor(x => x.Id)
#Html.CheckBoxFor(x => x.Delete)
<input #( "name=" + ViewData.TemplateInfo.HtmlFieldPrefix + ".FileBase") type="file" />
Note the usage of ViewData.TemplateInfo.HtmlFieldPrefix, it kinda sucks but like I said this is because of the poor mvc support for the file input type. We have to do it ourselves. We except the name for each file to be something like '[0].FileBase' etc.
This will populate the FileViewModel correctly on the POST action.
So far so good, what about validation?
Well again you can do that manually on the server. Test the file extensions yourself, and simply use the following to add the error to the model like:
ModelState.AddModelError("","Invalid extension.")
On another note, extension validation should be done on the client side (and as well as on the server side)

Related

DropDownList is not passing any values

Creating a dynamic drop down menu for US states that is being called via linq. When I select a state and then click submit i walk though the code and it shows that I am passing null. The list displays as it should, Any guidance will help.
If you need any more information please let me know and ill post it.
Controller
// GET:
[AllowAnonymous]
public ActionResult DealerLogin()
{
var results = (from a in db1.States
where a.CountryID == 221
select new SelectListItem { Value = a.StateID.ToString() , Text = a.Name }).ToList();
}
View
#using (Html.BeginForm())
{
#Html.AntiForgeryToken()
<div class="form-horizontal">
<hr />
#Html.ValidationSummary(true, "", new { #class = "text-danger" })
<div class="form-group">
<div class="form-group">
#Html.LabelFor(model => model.StateId, "States", htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-10">
#Html.DropDownListFor(model => model.StateId, Model.States.Items as List<SelectListItem>, "-- Select --", new { #class = "form-control" })
</div>
</div>
<div class="form-group">
<div class="col-md-offset-2 col-md-10">
<input type="submit" value="Create" class="btn btn-default" />
</div>
</div>
</div>
}
Model
public class EditProfile2
{
public int StateId { get; set; }
public SelectList States { get; set; }
}
UPDATED
Ok I have updates everything so it matches almost to #Fran answer, seems he was missing a few things but i got it to work. I also took what #Stephen Muecke said and got rid of the validation.
You seem to be going around all the built in stuff that MVC will give you for free.
Try this
You can use attributes to define what is required and to modify the display names without actually writing into your view.
ViewModel:
public class EditProfile2
{
[Required]
[DisplayName("State")]
public int StateId { get; set; }
public SelectList States {get;set;}
}
View: only including the relevant parts
Since we used attributes on our model, we don't have to give the text in the view. we can also use DropDownListFor instead of DropDownList. And also have this declaration add the "--Select State--" option
<div class="form-group">
#Html.LabelFor(model => model.StateId, htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-10">
#Html.DropDownListFor(model.StateId, Model.States, "-- Select State --", new { #class = "form-control" })
#Html.ValidationMessageFor(model => model.StateId, "", new { #class = "text-danger" })
</div>
</div>
Because of our previous use of attributes and built in framework elements, our action method can slim down.
Controller Action:
[AllowAnonymous]
public ActionResult DealerLogin()
{
var results = (from a in db1.States
where a.CountryID == 221
select new SelectListItem { Value= a.StateID.ToString(), Text = a.Name }).ToList();
return View(new EditProfile2 { States = new SelectList(results)});
}

Checkboxlist - on Post: Create - 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.

ASP.NET MVC Ajax file upload with jquery form plugin?

I use Jquery Ajax Form Plugin to upload file. Codes:
AuthorViewModel
public class AuthorViewModel
{
public int Id { get; set; }
[Required(ErrorMessage = "{0} alanı boş bırakılmamalıdır!")]
[Display(Name = "Yazar Adı")]
public string Name { get; set; }
[Display(Name = "Kısa Özgeçmiş")]
public string Description { get; set; }
[Display(Name = "E-Posta")]
public string Email { get; set; }
public string OrginalImageUrl { get; set; }
public string SmallImageUrl { get; set; }
}
Form
#using (Html.BeginForm("_AddAuthor", "Authors", FormMethod.Post, new { id = "form_author", enctype = "multipart/form-data" }))
{
<div class="editor-label">
<input type="file" name="file" id="file" />
</div>
<div class="editor-label">
#Html.LabelFor(model => model.Name)
</div>
<div class="editor-field">
#Html.EditorFor(model => model.Name)
</div>
<div class="editor-field">
#Html.ValidationMessageFor(model => model.Name)
</div>
...
<div class="submit-field">
<input type="submit" value="Ekle" class="button_gray" />
</div>
}
Script
<script>
$(function () {
$('#form_author').ajaxForm({
beforeSubmit: ShowRequest,
success: SubmitSuccesful,
error: AjaxError
});
});
function ShowRequest(formData, jqForm, options) {
$(".loading_container img").show();
}
function AjaxError() {
alert("An AJAX error occured.");
}
function SubmitSuccesful(result, statusText) {
// Veritabanı işlemleri başarılı ise Index sayfasına
// geri dön, değilse partial-view sayfasını yenile
if (result.url) {
window.location.href = result.url;
} else {
$(".authors_content_container").html(result);
}
}
</script>
Controller
[HttpPost]
public ActionResult _AddAuthor(AuthorViewModel viewModel, HttpPostedFileBase file)
{
...
viewModel.OrginalImageUrl = file.FileName;
...
}
Above codes work fine
Question
As you see, I post file seperate from ViewModel. Is there a way to add HttpPostedFileBase file property to ViewModel and bind it to viewModel in view, And post it to controller in ViewModel?
I hope , I can explain.
EDIT:
This codes work fine. I dont want post , viewModel and HttpPostedFile seperately. I want something like this: (If it is possible.)
Model
public class AuthorViewModel
{
public int Id { get; set; }
[Required(ErrorMessage = "{0} alanı boş bırakılmamalıdır!")]
[Display(Name = "Yazar Adı")]
HttpPostedFileBase file{ get; set; }
...
}
Controller
[HttpPost]
public ActionResult _AddAuthor(AuthorViewModel viewModel)
{
var file = viewModel.file;
...
}
Thanks.
Yes you can add AliRıza Adıyahşi.
Here is the property to do it:
public HttpPostedFileBase File { get; set; }
Now in you form you should add enctype as Xiaochuan Ma said:
#using (Html.BeginForm("_AddAuthor", "Authors", FormMethod.Post, new { id = "form_author", enctype="multipart/form-data" }))
{
<div class="editor-label">
<input type="file" name="file" id="file" />
</div>
<div class="editor-label">
#Html.LabelFor(model => model.Name)
</div>
<div class="editor-field">
#Html.EditorFor(model => model.Name)
</div>
<div class="editor-field">
#Html.ValidationMessageFor(model => model.Name)
</div>
...
<div class="submit-field">
<input type="submit" value="Ekle" class="button_gray" />
</div>
}
On you Controller action:
[HttpPost]
public ActionResult _AddAuthor(AuthorViewModel viewModel, HttpPostedFileBase file)
{
if(file!=null)
{
viewModel.File=file; //Binding your file to viewModel property
}
//Now you can check for model state is valid or not.
if(ModelState.IsValid)
{
//do something
}
else
{
return View(viewModel);
}
}
Hope it helps. Is this what you need ?
EDIT
There is nothing additional to do. Its automatically binding to viewModel.
[HttpPost]
public ActionResult _AddAuthor(AuthorViewModel viewModel)
{
var uploadedfile = viewModel.File;// Here you can get the uploaded file.
//Now you can check for model state is valid or not.
if(ModelState.IsValid)
{
//do something
}
else
{
return View(viewModel);
}
}
This worked for me !
Yes, you can add HttpPostedFileBase in to your ViewModel, and add enctype = "multipart/form-data" to your From in HTML.
Check with this link:
MVC. HttpPostedFileBase is always null

Can't add file upload capability to generated MVC3 page

I'm new to MCV and I'm learning MVC3. I created a model and a controller and view was generated for me. The generated code makes perfect sense to me. I wanted to modify the generated view and controller so that I could upload a file when I "create" a new record. There is a lot of good information out there about how to do this. Specifically I tried this: http://haacked.com/archive/2010/07/16/uploading-files-with-aspnetmvc.aspx
The problem is that even when I select a file (not large) and submit, there are no files in the request. That is, Request.Files.Count is 0.
If I create the controller and and view from scratch, in the same project (no model), the example works just fine. I just can't add that functionality to the generated page. Basically, I'm trying get the Create action to also send the file. For example, create a new product entry and send the picture with it.
Example Create view:
#model Product.Models.Find
#{
ViewBag.Title = "Create";
}
<h2>Create</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("Create", "Find", FormMethod.Post, new { enctype = "multipart/form-data" }))
{
#Html.ValidationSummary(true)
<fieldset>
<legend>Find</legend>
<input type="file" id="file" />
<div class="editor-label">
#Html.LabelFor(model => model.Title)
</div>
<div class="editor-field">
#Html.EditorFor(model => model.Title)
#Html.ValidationMessageFor(model => model.Title)
</div>
<div class="editor-label">
#Html.LabelFor(model => model.Description)
</div>
<div class="editor-field">
#Html.EditorFor(model => model.Description)
#Html.ValidationMessageFor(model => model.Description)
</div>
<p>
<input type="submit" value="Create" />
</p>
</fieldset>
}
<div>
#Html.ActionLink("Back to List", "Index")
</div>
Example Controller:
[HttpPost]
public ActionResult Create(Product product)
{
if (ModelState.IsValid)
{
if (Request.Files.Count > 0 && Request.Files[0] != null)
{
//Not getting here
}
db.Products.Add(product);
db.SaveChanges();
return RedirectToAction("Index");
}
return View(find);
}
This will create the record just fine but there are not files associated with the Request.
I've also tried a controller action like this:
[HttpPost]
public ActionResult Create(HttpPostedFileBase file)
{
if (file.ContentLength > 0)
{
//Not getting here
}
return RedirectToAction("Index");
}
I'm wondering if maybe you can't post a file at the same time as posting form fields? If that is the case, what are some patterns for creating a new record and associating a picture (or other file) with it?
Thanks
Create a ViewModel which has properties to handle your image and Product deatils
public class ProductViewModel
{
public string ImageURL { set;get;}
public string Title { set;get;}
public string Description { set;get;}
}
And in your HTTPGET Action method, return this ViewModel object to your strongly typed view
public ActionResult Create()
{
ProductViewModel objVM = new ProductViewModel();
return View(objVM);
}
And in your View
#model ProductViewModel
<h2>Add Product</h2>
#using (Html.BeginForm("Create", "Home", FormMethod.Post, new { enctype = "multipart/form-data" }))
{
#Html.TextBoxFor(m => m.Title) <br/>
#Html.TextBoxFor(m => m.Description ) <br/>
<input type="file" name="file" />
<input type="submit" value="Upload" />
#Html.HiddenFor(m => m.ImageURL )
}
Now in your HttpPost action method, accept this ViewModel and File
[HttpPost]
public ActionResult Create(HttpPostedFileBase file, ProductViewModel objVM)
{
if(file==null)
{
return View("Create",objVM);
}
else
{
//You can check ModeState.IsValid if you have to check any model validations and do further processing with the data here.
//Now you have everything here in your parameters, you can access those and save
}
}
You will have to create a ViewModel for Product (maybe ProductViewModel) and add a HttpPostedFileBase field with the same name as the field of the form and use that instead of the Product in the action of the controller.
A ViewModel is nothing but a model used for specific views. Most of the times, with extra data to generate the view or to decompose and form the model on the controller action.
public ProductViewModel
{
public string Cod { get; set; }
// All needed fields goes here
public HttpPostedFileBase File{ get; set; }
/// Empty constructor and so on ...
}

MVC binding to model with list property ignores other properties

I have a basic ViewModel with a property that is a List of complex types. When binding, I seem to be stuck with getting either the list of values, OR the other model properties depending on the posted values (i.e. the view arrangement).
The view model:
public class MyViewModel
{
public int Id { get; set; }
public string Property1 { get; set; }
public string Property2 { get; set; }
public List<MyDataItem> Data { get; set; }
}
public class MyDataItem
{
public int Id { get; set; }
public int ParentId { get; set; }
public string Name { get; set; }
public string Value { get; set; }
}
The controller actions:
public ActionResult MyForm()
{
MyViewModel model = new MyViewModel();
model.Id = 1;
model.Data = new List<MyDataItem>()
{
new MyDataItem{ Id = 1, ParentId = 1, Name = "MyListItem1", Value = "SomeValue"}
};
return View(model);
}
[HttpPost]
public ActionResult MyForm(MyViewModel model)
{
//...
return View(model);
}
Here is the basic view (without the list mark-up)
#using (Html.BeginForm()) {
#Html.ValidationSummary(true)
<fieldset>
<legend>My View Model</legend>
#Html.HiddenFor(model => model.Id)
<div class="editor-label">
#Html.LabelFor(model => model.Property1)
</div>
<div class="editor-field">
#Html.EditorFor(model => model.Property1)
#Html.ValidationMessageFor(model => model.Property1)
</div>
<div class="editor-label">
#Html.LabelFor(model => model.Property2)
</div>
<div class="editor-field">
#Html.EditorFor(model => model.Property2)
#Html.ValidationMessageFor(model => model.Property2)
</div>
<p>
<input type="submit" value="Save" />
</p>
</fieldset>
}
When posted back to the controller, I get the 2 property values and a null value for the 'Data' property as expected.
If I add the mark-up for the List as follows (based on the information in this Scott Hanselman post and Phil Haack's post):
<div class="editor-field">
#for (int i = 0; i < Model.Data.Count(); i++)
{
MyDataItem data = Model.Data[i];
#Html.Hidden("model.Data[" + i + "].Id", data.Id)
#Html.Hidden("model.Data[" + i + "].ParentId", data.ParentId)
#Html.Hidden("model.Data[" + i + "].Name", data.Name)
#Html.TextBox("model.Data[" + i + "].Value", data.Value)
}
</div>
The 'Data' property of the model is successfully bound but the other properties are null.
The form values posted are as follows:
Id=1&Property1=test1&Property2=test2&model.Data%5B0%5D.Id=1&model.Data%5B0%5D.ParentId=1&model.Data%5B0%5D.Name=MyListItem1&model.Data%5B0%5D.Value=SomeValue
Is there a way to get both sets of properties populated or am I just missing something obvious?
EDIT:
For those of you who are curious. Based on the answer from MartinHN, the original generated mark-up was:
<div class="editor-field">
<input id="model_Data_0__Id" name="model.Data[0].Id" type="hidden" value="1" />
<input id="model_Data_0__ParentId" name="model.Data[0].ParentId" type="hidden" value="1" />
<input id="model_Data_0__Name" name="model.Data[0].Name" type="hidden" value="MyListItem1" />
<input id="model_Data_0__Value" name="model.Data[0].Value" type="text" value="SomeValue" />
</div>
The new generated mark-up is:
<div class="editor-field">
<input id="Data_0__Id" data-val="true" name="Data[0].Id" type="hidden" value="1" data-val-number="The field Id must be a number." data-val-required="The Id field is required." />
<input id="Data_0__ParentId" name="Data[0].ParentId" type="hidden" value="1" data-val="true" data-val-number="The field ParentId must be a number." data-val-required="The ParentId field is required." />
<input id="Data_0__Name" name="Data[0].Name" type="hidden" value="MyListItem1" />
<input id="Data_0__Value" name="Data[0].Value" type="text" value="SomeValue" />
</div>
Which results in the following posted values:
Id=1&Property1=test1&Property2=test2&Data%5B0%5D.Id=1&Data%5B0%5D.ParentId=1&Data%5B0%5D.Name=MyListItem1&Data%5B0%5D.Value=SomeValue
Notice there's no 'model.' in the name and posted values...
Try to change the code for the Data collection to this, and let MVC take care of the naming:
<div class="editor-field">
#for (int i = 0; i < Model.Data.Count(); i++)
{
#Html.HiddenFor(m => m.Data[i].Id)
#Html.HiddenFor(m => m.Data[i].ParentId)
#Html.HiddenFor(m => m.Data[i].Name)
#Html.TextBoxFor(m => m.Data[i].Value)
}
</div>
Alternatively you could have created an EditorTemplate for your nested ViewModel as follows.
#model MyDataItem
#Html.HiddenFor(model => model.Id)
#Html.HiddenFor(model => model.ParentId)
#Html.HiddenFor(model => model.Name)
#Html.TextBoxFor(model => model.Value)
Create a folder named 'EditorTemplates' in your 'Shared' folder and save the above as 'MyDataItem.cshtml'.
Then in your View, just call the following instead of the foreach loop:
#Html.EditorFor(model => model.Data)
Feels a bit less hackier IMO :)
Just my 2 cents but something worth noting with this issue - the data member in the View Model must be defined as a public property for the postback model binding to work.
I had a very similar problem to the above but used a public data member in my View Model. The same HTML is generated as shown above and all looks well but the model binder threw back an empty collection. Worth watching for...

Resources