在.NET MVC中使用@Ajax.BeginForm上传图像?



我想在我的应用程序中使用Ajax.BeginForm上传图像。

目前HttpPostedFileBase file正在获得价值0。任何人请在这里引导我。

我试过这段代码,但文件没有上传。

如果有人可以为此提供一些解决方案,我们将不胜感激。如果我使用 @Html.BeginForm,那么它可以工作,但我想使用 @Ajax.BeginForm。

public class ClsUpload
{
public string FilePath { get; set; }
}

控制器

public ActionResult Edit(ClsUpload model,HttpPostedFileBase file)
{
if (Request.Files.Count > 0)
{
file = Request.Files[0];
if (file != null && file.ContentLength > 0)
{
string fileName = Path.GetFileName(file.FileName);
string path = Path.Combine(Server.MapPath("/Content/Images/"), fileName);
file.SaveAs(path);
model.FilePath = path;
}   
}
try
{
UploadDetials details = new UploadDetials();
details.UpdateDetails(model);
return RedirectToAction("Index");
}
catch
{
return RedirectToAction("Index");
}
}

部分视图

@model XX.X.Models.File.ClsUpload
@using (Ajax.BeginForm(new AjaxOptions { UpdateTargetId = "partial", InsertionMode = InsertionMode.Replace }))
{ 
@Html.HiddenFor(model => model.FilePath)
<input type="file" name="file" />
<img src=@Model.FilePath alt="Image" />
<input type="submit" value="Save" />
}   

您可以使用FormMethod.Post、new { enctype = "multipart/form-data" }( 和[AcceptVerbs(HttpVerbs.Post(]更新代码,如下所示

在部分视图中

@using (Html.BeginForm("ActionMethod1", "Controller", FormMethod.Post, new { enctype = "multipart/form-data" }))
{
}

在控制器中

[AcceptVerbs(HttpVerbs.Post)]
public ActionResult ActionMethod1(HttpPostedFileBase pic)
{
}

这很旧,但我想展示我如何使用 Ajax.BeginForm(( 完成上传文件。 基本上,重载会告诉你什么是可能的。 我将重载用于:"string actionName, string controllerName, object routeValues, AjaxOptions ajaxOptions, object htmlAttributes"。 注意:我使用 null 表示"路由值"。

下面是一个代码示例:

@using (Ajax.BeginForm("UploadFile", "Home", null, new AjaxOptions { HttpMethod = "POST", UpdateTargetId = "MyIDToUpdate", OnSuccess = "EditSuccessClearForm('IDToClear', '')", OnFailure = String.Format("NewGenericFailure(xhr, '{0}')", "#IDToPassThisFunction"), InsertionMode = InsertionMode.ReplaceWith }, new { enctype = "multipart/form-data", @id = "NewFileFormID" }))
{
@Html.AntiForgeryToken()
<div class="row">
<div class="col-sm-8 col-sm-offset-1">
@Html.TextBox("file", "", new { type = "file", accept = ".jpg, .jpeg, .png, .pdf", @id = fileID, onchange = VerifySizeOfFile })
</div>
<div class="col-sm-2">
<button type="submit" id="FileSubmitButton" class="btn btn-primary">Upload</button>
</div>
</div>
}

最新更新