Search code examples
jqueryajaxasp.net-mvcrazorhtml-helper

Posting MVC Razor form from ajax


Within a Partial View, there is a form(@addName) using Html.Helper classes (TextBoxFor, DropDownListFor, etc).

@model Models.ADP

using (@Html.BeginForm(new { id= @addName}))
{
    @Html.TextBoxFor(model => model.EndValue, new { id = @newName, size = "5", style = "margin-right: 10px" })
    @Html.HiddenFor(model => model.ModuleTypeId, new { @Value = @ViewBag.ModuleId }
    @Html.DropDownListFor(model => model.DPId, @dpList, "Choose an Option...", new { @class = "select" })
}

I intercept the submit in order to post and retrieve new data asynchronously, divId is the div for the whole Partial View.

    $('#@saveName').click( function (event) {
        event.preventDefault();
        $.ajax({
            url: '@Url.Action("SaveADP", "Dispense")',
            type: 'POST',
            data: $('#@addName').serialize(),
            success: function (data) {
                $('#@divId').html(data);
            }
        })
    })

The SaveADP action is being called, but the only field with a set value is EndValue, the other fields(ModuleTypeId and DPId) have the default values instead of their form values. What am I doing wrong here?


Solution

  • The ASP.NET MVC agnostic way to do it is to give id for each elements and then pass it to the controller as JSON. As its a partial, it would be better suited for your need as the response could be fetched on the callback of the ajax request.

    Example

    var DTO = {
        newDP: {
            StartValue: $("#id_of_elm").val(),
            EndValue: $("#newName").val(),
            Duration: $("#id_of_elm").val(),
            ModuleTypeId: $("#id_of_elm").val(),
            DPId: $("#id_of_elm").val()
        }
    };
    
    $('#saveName').click(function (event) {
        event.preventDefault();
        $.ajax({
            contentType: 'application/json'
            data: JSON.stringify(DTO),
            type: 'POST',
            url: '@Url.Action("SaveADP", "Dispense")'
        }).done(function (data) {
            $('#divId').html(data);
        });
    });
    

    Unrelated, but important points

    1. Please use #saveName instead of #@saveName and #divId instead of #@divId
    2. Please note that jqXHR.done() is the new way of handling success callback in $.ajax