我想要使用Razor engine
asp.net mvc 5
使用Upload control
保存圖像。這些是我的代碼下面,我認爲每一件事情都可以,但我不知道爲什麼UploadImage
在controller
得到空,並沒有得到選定的圖像。請任何人幫助我嗎?Ajax上傳幫手在asp.net mvc 5沒有工作,並得到空值
管理控制器
根據文章我在控制器參數使用相同的名稱@html.upload("UploadImage")
。
[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
根據文章中,我添加enctype="multipart/form-data"
到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());
}
}
subGood參數爲空嗎?你的提交按鈕在Ajax形式? –
'Ajax.BeginForm'不允許上傳文件。 –
看看這個:http://blueimp.github.io/jQuery-File-Upload/ –