Friday, September 16, 2011

upload a file in asp.net MVC along with other components in your view

Hi,

I am here going to describe how to upload a file in asp.net MVC along with other components in your view. The view is a content page.

let us take an example of an item object I will write here some portions of viewmodel, view page and controller function.

ViewModel:


[Required(ErrorMessage = "Item Code Required")]
[StringLength(50, ErrorMessage = "Must be less than 51 characters")]
public string i_code
{
get;
set;
}

[Required(ErrorMessage = "Item Name Required")]
[StringLength(50, ErrorMessage = "Must be less than 51 characters")]
public string i_name
{
get;
set;
}

public HttpPostedFileBase Image
{
get;
set;
}





View:

'

<% using (Html.BeginForm("Create","items",FormMethod.Post, new {enctype = "multipart/form-data"}))
{%>

<% =ViewData["Result"] %>
<%: Html.ValidationSummary(true)%>



<%: Html.LabelFor(model => model.i_code) %>
<%: Html.TextBoxFor(model => model.i_code) %>
<%: Html.ValidationMessageFor(model => model.i_code) %>

<%: Html.LabelFor(model => model.i_name) %>
<%: Html.TextBoxFor(model => model.i_name) %>
<%: Html.ValidationMessageFor(model => model.i_name) %>

<%: Html.LabelFor(model => model.FileUpload) %>
input type="file" id="Image" name="Image"

input type="submit" value="Create"


<% } %>'




Controller Function:

[HttpPost]
[AcceptVerbs(HttpVerbs.Post)]
public ActionResult Create( itemviewmodel ToCreate)
{

if (ToCreate.Image.ContentLength > 0)
{
string filePath = Path.Combine(HttpContext.Server.MapPath("../bin/Uploads"),
Path.GetFileName(ToCreate.Image.FileName.Replace(' ','_')));
ToCreate.Image.SaveAs(filePath);
ToCreate.i_imgpath = filePath;
}

_entities.AddToitems(m);
_entities.SaveChanges();

}


The things to be more careful are

1). Using a correct version of Html.BeginForm function(see above) and
2). Input type file should have "id" and "name" same value as the name of your viewmodel property field for file upload.
3). Make sure you have given sufficient permissions to the Network service or IUser Account for the folders where images will be stored, this is a common problem after deployment to many developers.

Further one more thing to be kept in mind is that your master page also has a
tag which will cause the
tag of the content page to be bypassed, to overcome this problem, remove
tag from the master page.


hope you will find this post helpful.
wish you good luck with file uploading.