I want to post a Html.BeginForm with data and a file and replace the content with the new data. I have done it with only data.
JQuery with success but only with data.
$('form').submit(function () {
if ($(this).valid()) {
$.ajax({
url: this.action,
type: this.method,
data: $(this).serialize(),
success: function (result) {
// Element is a div.
$(element).html(result);
}
});
}
return false;
});
I have been tryin for 8 hours now and came up with this. But it redirects me to a new page, when it should update the div. Everything else work as it should. Like upload the file and data. It just redirect me to a new page. And i am going crazy.
I use unobtrusive and validate.min. I can validate the form and get it to update "WHITOUT THE FILEUPLOAD"
My Approach after 8 hours...
ParticalView
@using Website.Models
@model MySuperModel
@if (Model != null)
{
using (Html.BeginForm("Action", "Controller", null, FormMethod.Post, new { enctype = "multipart/form-data", id = "helpme", @class = "please" }))
{
@Html.AntiForgeryToken()
// Some code..
}
}
Controller
[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult Action(MySuperModel Model, HttpPostedFileBase file)
{
// Some file validation
if (ModelState.IsValid)
{
// Updating the database and sets Model to its new values.
}
return PartialView("Action", Model);
}
Also tried
return View(Model);
return ParticalView(Model);
return ParticalView("~/Views/SecretService/Action.cshtml", Model);
JQuery
$('form').submit(function () {
if ($(this).valid()) {
$(this).ajaxForm({
beforeSend: function () {
// Doing some loading gif stuff
},
success: function (result) {
// element is div holding the ParticalView
$(element).html(result);
},
complete: function () {
$.validator.unobtrusive.parse('form');
// And so on.
}
});
}
return false;
});
I have cuttet the code down abit to make it more readable. I hope someone can help.