Roshan
Roshan

Reputation: 3384

How to pass model to controller action using ajax call?

Im using ajax call to pass model data in to my controller action , but controller receives empty model when I call via ajax , Here is my controller

[HttpPost]
public ActionResult Edit( int id, ALDS.Web.Areas.Direct2M3.Models.ItemInputModel collection)
{
    try
    {
        // TODO: Add update logic here
        return View("Index");
    }
    catch
    {
        return View();
    }
}

And here is my input model

public class ItemInputModel
{
    [Key]
    public long ID { get; set; }
    [DisplayName("Buyer Code")]
    public string ModelCode { get; set; }
    [DisplayName("BOM Description")]
    public string BOMDescription { get; set; }
    //BUYER CODE
    [DisplayName("UOM")]
    public string UOM { get; set; }
    [DisplayName("Alternative UOM")]
    public string AltUOM { get; set; }
    [DisplayName("Garment Color Wise")]
    public string ColorWise { get; set; }
    [DisplayName("Garment Size Wise")]
    public string SizeWise { get; set; }
    [DisplayName("RM Color Wise")]
    public string RMcolorWise { get; set; }
    [DisplayName("RM Size Wise")]
    public string RMsize { get; set; }
    [DisplayName("Procument Group")]
    public string BrandixProcurementGroupCode { get; set; }
    [DisplayName("Designation CPT")]
    public string DesignationCPT { get; set; }
    [DisplayName("Item Name")]
    public string ItemName { get; set; }
    [DisplayName("Fabric Composition")]
    public string FabricComposition { get; set; }
    [DisplayName("Hierachy Code ")]
    public string HierarchyCode { get; set; }
    [DisplayName("GSM Value")]
    public string GSMValue { get; set; }
    [DisplayName("RM Width")]
    public string RMWidth { get; set; }
}

Here is my ajax call from the view

$.ajax({
    type: 'POST',
    dataType: 'application/json; charset=utf-8',
    cache: false,
    url: '/ItemMaster/Edit',
    data:{ id: collection.ID, collection:collection},
    success: function (data, textStatus, jqXHR) {
        alert("ok");
        //Do Stuff 
        //$("#DailyInvoiceItems").html(data.Id);
    },
    error: function (jqXHR, textStatus, errorThrown) {
        alert('Failed');
        //Do Stuff or Nothing
    }
});

and im using this model to pass to the action from the , ajax

var model = {
    ID: $('#ID').val(),
    ModelCode: $('#txtModelCode').val(),
    BOMDescription: $('#txtBOMDescription').val(),
    UOM: $('#txtUOM').val(),
    AltUOM: $('#txtAltUOM').val(),
    ColorWise: $('#ddnColorWise').val(),
    SizeWise: $('#ddnSizeWise').val(),
    RMcolorWise: $('#ddnRMcolorWise').val(),
    RMsize: $('#ddnRMsize').val(),
    BrandixProcurementGroupCode: $('#ddnBrandixProcurementGroupCode').val(),
    DesignationCPT: $('#txtDesignationCPT').val(),
    ItemName: $('#txtItemName').val(),
    FabricComposition: $('#txtFabricComposition').val(),
    HierarchyCode: $('#txtHierarchyCode').val(),
    GSMValue: $('#txtGSMValue').val(),
    RMWidth: $('#txtRMWidth').val()
};

I put a break point inside the action method and inspect the collection parameter but it is an empty input object , with null properties ! Can anyone help me???? Thankz,.

Upvotes: 1

Views: 23747

Answers (1)

user3559349
user3559349

Reputation:

There are a number of errors with ajax code. First your method returns html (a view - although it should be a partial view) so it need to be dataType: 'html', or you can omit it altogether. Second because your sending an object containing objects, you would need to stringify the data (using data: JSON.stringify({ id: collection.ID, collection: model}), and add the contentType: 'application/json; charset=utf-8', option (note the name of your javascript object is model, not collection.

However most of this code is unnecessary. Your model already contains a property long ID so there is no need to post and bind it twice and you controller method can be just

[HttpPost]
public ActionResult Edit(ItemInputModel model)
{
    ....
    return PartialView(..), // not View(..)
}

Assuming you have generated your form controls correctly using the strongly typed HtmlHelper methods, for example

@Html.HiddenFor(m => m.ID)
@Html.TextBoxFor(m => m.ModelCode)
.... 

then you can use the .serialize() method to correctly serialize all the form controls, so that your ajax becomes

var data = $('form').serialize(); // or use the id of the form is you have given it one
$.ajax({
    type: 'POST',
    dataType: 'html', // this can be omitted - the ajax() function will work it out
    cache: false,
    url: '/ItemMaster/Edit',
    data: data,
    success: function (data, textStatus, jqXHR) {
        ... // append the partial view you return to the DOM?
    },
    error: function (jqXHR, textStatus, errorThrown) {
        ....
    }
});

Side note: You should always use Url.Action() to generate the correct url's, for example url: '@Url.Action("Edit", "ItemMaster")',. If this script is in an external file, then generate it in the main view (e.g. as a data-* attribute an the button element your handling) and pass it to the function.

Upvotes: 5

Related Questions