Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

MVC3 Razor Ajax Form Submit

I use The MVC3 Helper to generate my Ajax form like this:

@using (Ajax.BeginForm("Attended", "Lesson", new AjaxOptions
               {
                   HttpMethod = "GET",
                   InsertionMode = InsertionMode.InsertAfter,
                   UpdateTargetId = "mdl" + item.ID
               }))
            {
                @Html.HiddenFor(modelItem => item.ID);
                @Html.CheckBox("Attended", item.Attended, new { OnChange = "javascript:this.form.submit()"});
            }

I just don't find the proper way to submit the Form on the change event of the checkbox. I don't want my users to click the submit button.

The HTMLAttribute works, but on the change a postback happens instead of an ajax request.

Does anybody know the answer?

like image 724
Manuel Avatar asked Aug 30 '11 12:08

Manuel


3 Answers

First, create a submit button inside your form, and hide it by setting the attribute style="display:none;". Then, instead of using this.form.submit() in your onchange event, use the following:

$(this).parents('form:first').find(':submit')[0].click();

This will invoke the jquery.unobtrusive-ajax.js script, and complete your Ajax submission.

like image 55
counsellorben Avatar answered Nov 17 '22 16:11

counsellorben


this may help

@Html.CheckBox("Attended", item.Attended, new { OnChange = "submitForm"});

function submitForm(e)
{
    document.forms[0].submit();
}
like image 42
Mandoleen Avatar answered Nov 17 '22 18:11

Mandoleen


What about using jQuery to trigger the submit? Like in this answer How to post ASP.NET MVC Ajax form using JavaScript rather than submit button

Using the .change() event instead of the .click() event the jQuery part would look something like this:

$(function() {
    $('form#ajaxForm').find('input.submit').change( function() {
         $('form#ajaxForm').trigger('submit');
    });
}
@using (Ajax.BeginForm("Attended", "Lesson", new { id = Model.Id }, new AjaxOptions
        {
           HttpMethod = "GET",
           InsertionMode = InsertionMode.InsertAfter,
           UpdateTargetId = "mdl" + item.ID
        }, new { id = "ajaxForm" } ))
{
   @Html.HiddenFor(modelItem => item.ID);
   @Html.CheckBox("Attended", item.Attended, new { @class = "submit"});
}

This is totally untested code so beware of typos :)

like image 1
Tor-Erik Avatar answered Nov 17 '22 17:11

Tor-Erik