Trying to upload a file with mvc4 and im getting null returned in my controller for the file upload. Can anyone see why please?
View Model
public class PostExtendedWithImage
{
public Post post { get; set; }
public HttpPostedFileBase file { get; set; }
}
View
@using (Ajax.BeginForm("CreatePost", "Wall", new AjaxOptions
{
HttpMethod = "post",
InsertionMode = System.Web.Mvc.Ajax.InsertionMode.InsertBefore,
UpdateTargetId = "newPost"}))
{
@Html.AntiForgeryToken()
@Html.ValidationSummary(true)
<fieldset>
<legend>Post</legend>
<div class="editor-label">
</div>
<div class="editor-field">
@Html.HiddenFor(model => model.post.Username, new { Value = User.Identity.Name })
</div>
@Html.FileFor(model => model.file)
<div class="editor-label">
@Html.LabelFor(model => model.post.PostContent)
</div>
<div class="editor-field">
@Html.EditorFor(model => model.post.PostContent)
@Html.ValidationMessageFor(model => model.post.PostContent)
</div>
@{
TempData["returnURL"] = Request.Url.AbsoluteUri;
}
<p>
<input type="submit" id="postStatus" value="Create" />
</p>
</fieldset>
}
Controller
[HttpPost]
[ValidateAntiForgeryToken]
public PartialViewResult CreatePost(PostExtendedWithImage VM)
{
if (ModelState.IsValid)
{
if (VM.file == null)
{
// Do stuff
}
else
{
//Save file to DB
}
return PartialView("_NewStatusPartial",VM);
}
return PartialView("All",VM);
}
Asynchronous File submission using Ajax.BeginForm
may not be possible. You can use 3rd party plugins to do this ajax submission.
You can use jQuery Forms Plugin in this context. See how can you do this using this plugin.
// bind to the form's submit event
$('#myForm2').submit(function() {
// inside event callbacks 'this' is the DOM element so we first
// wrap it in a jQuery object and then invoke ajaxSubmit
$(this).ajaxSubmit(options);
// !!! Important !!!
// always return false to prevent standard browser submit and page navigation
return false;
});
Its so simple to do. Give a try!
I'm not too familiar with Ajax.BeginForm
, however, if you are uploading a file, you usually need to add enctype="multipart/form-data"
to the <form>
tag.
Not really sure if this applies in AJAX.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.