I am learning ASP.NET MVC and I am confused between use of AJaxform or Jquery. With some answers on google I am able to understand that JQuery is a better option but still confuse why?
Here is my code for uploading file via JQuery, which is going to my controller but I am getting null for both HttpPostedFileBase file, CreatePost post
Model
public class CreatePost
{
public string userImage { get; set; }
}
Controller
[HttpPost]
public ActionResult Index(HttpPostedFileBase file, CreatePost post )
{
var test = post.userImage;
if (file != null && file.ContentLength > 0)
{
var fileName = Path.GetFileName(file.FileName);
var path = Path.Combine(Server.MapPath("~/Content/Images"), fileName);
file.SaveAs(path);
}
return RedirectToAction("Index");
}
View
<script type="text/javascript">
$(function () {
$('form').submit(function () {
if ($(this).valid()) {
$.ajax({
url: this.action,
type: this.method,
data: $(this).serialize(),
success: function (result) {
$('#result').html(result);
}
});
}
return false;
});
});
</script>
@using (Html.BeginForm("Index", "Home", FormMethod.Post, new { nctype = "multipart/form-data" }))
{
<div class="editor-label">
@Html.LabelFor(model => model.userImage)
</div>
<input type="file" name="file"/>
<input type="submit" value="OK" />
<div id="result"></div>
}
Why I am getting null for file and post?