1

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.

  • If your wanting to submit a for and files using ajax, refer [this answer](http://stackoverflow.com/questions/29293637/how-to-append-whole-set-of-model-to-formdata-and-obtain-it-in-mvc/29293681#29293681) –  Aug 23 '15 at 00:58
  • Thanks for replying. is it possible to do it with Html.BeginForm() ? – The Almighty Bobo Aug 23 '15 at 13:40
  • Of course, But you don't really need `Html.BeginForm()` if your posting the form using ajax. If you want to make a normal form submit, then you just need to add the `enctype="multipart/form-data"` attribute to the form (and delete your script) –  Aug 23 '15 at 13:44
  • @Stephen Muecke - When i removed Html.BeginForm and wrote plain html, it worked. place an answer and i will accept. and then i will post what i did for future referrences. – The Almighty Bobo Aug 23 '15 at 15:03

2 Answers2

3

Thanks to @Stephen Muecke i got it to work.

For future refferences.

View

-Replace-
using (Html.BeginForm("Action", "Controller", null, FormMethod.Post, new { enctype = "multipart/form-data", id = "helpme", @class = "please" }))
-With-
<form action="@Url.Action("Action", "Controller")" id="helpme" enctype="multipart/form-data" class="please" method="post">

JQuery

$('form').submit(function (event) {

    /*
        First it dinnt work until i prevented the server side form submit.
        So this may actual work with @Html.BeginForm()
        But i dinnt have the energy to try it, since i got it to work.
    */
    event.preventDefault();

    if ($(this).valid())
    {
        var formdata = new FormData($(this).get(0));

        $.ajax({
            url: this.action,
            type: this.method,
            data: formdata,
            processData: false,
            contentType: false,
            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;
});

Now it works.

-1

Hello you should use JsonResult instead of ActionResult for ajax calls. ActionResult will always lead to page refresh.

[HttpPost]
[ValidateAntiForgeryToken]
public JsonResult Action(MySuperModel Model, HttpPostedFileBase file)
{           
        // Some file validation

        if (ModelState.IsValid)
        {
            // Updating the database and sets Model to its new values.                    
        }

    return (result.ToHtmlString(), JsonRequestBehavior.AllowGet)
}
funkyCatz
  • 119
  • 1
  • 2
  • Nonsense. `JsonResult` is `ActionResult` ! And OP is calling the method using an ajax call so it will NEVER lead to a page refresh. And what on earth is `result.ToHtmlString()` - you code would just throw an exception ! –  Aug 23 '15 at 07:55
  • First of all. Thanks for replying and tryin to help me out. But i cannot seem to understand your .ToHtmlString(). But i did try to change it to JsonResult and return a JSON string and replace the div just with that. But it still redirects me to a new page. – The Almighty Bobo Aug 23 '15 at 13:00