I want to save image using Upload control
in asp.net mvc 5
using Razor engine
. These are my codes below , I think every thing is OK but I don't know why UploadImage
in controller
gets null and didn't get selected image . could any one help me please ?
admin controller
according to a article I used same name @html.upload("UploadImage")
in controller parameters.
[HttpPost]
public ActionResult AddSubGood(SubGood subgood, HttpPostedFileBase UploadImage)
{
var MainGoodId = subgood.FKMainGoodID;
SubGoodRepositories blSubGood = new SubGoodRepositories();
if (ModelState.IsValid)
{
subgood.FKMainGoodID = MainGoodId;
if (blSubGood.Add(subgood))
{
return MessageBox.Show("added successfully", MessageType.Success);
}
else
{
return MessageBox.Show(" didn't add", MessageType.Error);
}
}
else
{
return MessageBox.Show(ModelState.GetErrors(), MessageType.Warning);
}
}
AddSubGood.cshtml
according to a article, I added enctype="multipart/form-data"
to form
@using (Ajax.BeginForm("Admin", "AddSubGood", new AjaxOptions { HttpMethod = "Post", Url = "/Admin/AddSubGood" }, new{enctype="multipart/form-data" }))
{
@Html.AntiForgeryToken()
<div class="form-group">
<div class="form-group">
<div class="col-md-10">
@Html.Upload("UploadImage")
@Html.ValidationMessageFor(model => model.SubGoodURL)
</div>
@Html.LabelFor(model => model.SubGoodURL, new { @class = "control-label col-md-2" })
</div>
}
UploadHelper.cs
public static class UploadHelper
{
public static MvcHtmlString Upload(this HtmlHelper helper, string name, object htmlAttributes = null)
{
TagBuilder input = new TagBuilder("input");
input.Attributes.Add("type", "file");
input.Attributes.Add("id", helper.ViewData.TemplateInfo.GetFullHtmlFieldId(name));
input.Attributes.Add("name", helper.ViewData.TemplateInfo.GetFullHtmlFieldName(name));
if (htmlAttributes != null)
{
var attributes = HtmlHelper.AnonymousObjectToHtmlAttributes(htmlAttributes);
input.MergeAttributes(attributes);
}
return new MvcHtmlString(input.ToString());
}
public static MvcHtmlString UploadFor<TModel, TValue>(this HtmlHelper<TModel> helper, Expression<Func<TModel, TValue>> expression, object htmlAttributes = null)
{
//helper.ViewContext.ViewData.TemplateInfo.GetFullHtmlFieldName(ExpressionHelper.GetExpressionText(expression))
var data = ModelMetadata.FromLambdaExpression(expression, helper.ViewData);
TagBuilder input = new TagBuilder("input");
input.Attributes.Add("type", "file");
input.Attributes.Add("id", helper.ViewData.TemplateInfo.GetFullHtmlFieldId(ExpressionHelper.GetExpressionText(expression)));
input.Attributes.Add("name", helper.ViewData.TemplateInfo.GetFullHtmlFieldName(ExpressionHelper.GetExpressionText(expression)));
if (htmlAttributes != null)
{
var attributes = HtmlHelper.AnonymousObjectToHtmlAttributes(htmlAttributes);
input.MergeAttributes(attributes);
}
return new MvcHtmlString(input.ToString());
}
}