1

I've faced a problem with receiving data after jQuery post request to the MVC action. I have standart scenario. I have to collect some information from user and sent it to the action to add this data to the datasource and return id of the new entry to the UI for further use.

jQuery

$('#somediv').on('click', '.Save', function () {
    var data = $(this).closest('form').serialize();
    $.post('/home/add', data, function (data) {
        $('#div-container').html(data);            
    });
});

MVC action

[HttpPost]
public ActionResult Add(Data data)
{
    Data addedData = logic.Add(data);
    ViewData.Model = addedData;
    return PartialView("PatrialView");
}

Partial View

@model MyClass.Data

@using (Html.BeginForm())
{
        <div id="div-container">
            @Html.HiddenFor(model => Model.Id)                
            @Html.TextBoxFor(model => Model.Name)                
        </div>

        <input type="button" class="btn Save" value="Save" />
    </div>
</li>
}

Also Home controller has an filter to disable cache.

[OutputCache(NoStore = true, Duration = 0, VaryByParam = "*")]

Correct data comes to action. ViewData.Model contains right id before partial view is called. Also I debuged through the view and data is set to the controls correctly, but response body (checked by IE Dev Tool) is with id = 0. Could you please advise what can be wrong with my code?

Pylyp Lebediev
  • 1,991
  • 4
  • 26
  • 44

0 Answers0