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.

4
  • If your wanting to submit a for and files using ajax, refer this answer Commented Aug 23, 2015 at 0:58
  • Thanks for replying. is it possible to do it with Html.BeginForm() ? Commented Aug 23, 2015 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) Commented Aug 23, 2015 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. Commented Aug 23, 2015 at 15:03

2 Answers 2

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.

Sign up to request clarification or add additional context in comments.

Comments

-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)
}

2 Comments

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 !
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.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.