0

I have two view models as below

public class hdr_doc_upload
{
    public string document_name { get; set; }
    public HttpPostedFileBase UpFile { get; set; }
}

public class list_doc
{
    public List<hdr_doc_upload> hdr_doc_upload { get; set; }
}

Controller

public ActionResult Create_Group()
{
    list_doc list = new list_doc();
    return View(list);
}

View

@Html.TextBoxFor(model => model.hdr_doc_upload[0].document_name)
<input type="file" id="hdr_doc_upload[0].UpFile" name="hdr_doc_viewmodel[0].UpFile" />
@Html.TextBoxFor(model => model.hdr_doc_upload[1].document_name)
<input type="file" id="hdr_doc_upload[1].UpFile" name="hdr_doc_viewmodel[1].UpFile" />

Give me below screen

enter image description here

but when i submit the page we only getting the textbox values the file is getting as null. enter image description here

Sachu
  • 7,555
  • 7
  • 55
  • 94
  • `name="hdr_doc_viewmodel[0].UpFile` has no relationship to your model (its `hdr_doc_upload`, not `hdr_doc_viewmodel`) –  Feb 28 '17 at 08:49
  • 1
    And generate it correctly using `@Html.TextBoxFor(m => m.hdr_doc_upload[i].UpFile, new { type = "file" })` inside a `for` loop and add 2 items to you collection in the GET method –  Feb 28 '17 at 08:51
  • @StephenMuecke actually number of files will be dynamic..is it possible to create a button and generate the same dynamically? – Sachu Feb 28 '17 at 08:53
  • Refer [this answer](http://stackoverflow.com/questions/28019793/submit-same-partial-view-called-multiple-times-data-to-controller/28081308#28081308) for a couple of options –  Feb 28 '17 at 08:54
  • @StephenMuecke thank u.. – Sachu Feb 28 '17 at 08:59

1 Answers1

1

Your creating manual <input> elements that have name attributes that do not relate to your model. The attributes needs to be

name="hdr_doc_upload[0].UpFile" // not hdr_doc_viewmodel[0].UpFile

However, you should be generating you control for the file input correctly using the strongly typed TextBoxFor() method, inside a for loop.

In your controller, populate your model with 2 new instances of hdr_doc_upload before passing the model to the view

list_doc list = new list_doc()
{
    new list_doc(),
    new list_doc()
};
return View(list);

and then in the view

for(int i = 0; i < Model.Count; i++)
{
    @Html.TextBoxFor(model => model.hdr_doc_upload[i].document_name)
    @Html.TextBoxFor(model => model.hdr_doc_upload[i].UpFile, new { type = "file" })
}