Sachu
Sachu

Reputation: 7766

file uploading through view model coming as null

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

Upvotes: 0

Views: 103

Answers (1)

user3559349
user3559349

Reputation:

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" })
}

Upvotes: 1

Related Questions