2
votes

I have been trying to make Ajax post but data always getting Null at Controller side. Pls Help:-

**Model:-**
public class UpdateProxyTracker
    {    
        public string Test_Reference_Id { get; set; }
        public string Owner { get; set; }
        public string Remarks { get; set; }        
        public string Status { get; set; }        
    }

**View:** 
@using (Html.BeginForm("UpdateTracker", "Home", FormMethod.Post, new { id = "optionForm" }))
{ 
<div>
        <fieldset style="background-color: #FFFFFF">
            <legend>Update Details</legend>
            <table>
                <tr>
                    <td>Test Ref Id</td>
                    <td>
                        <input id="testrefId" readonly="readonly" type="text" [email protected]_Reference_Id>
                    </td>
                </tr>
......
...
}

**JQuery:**
$(document).ready(function () {
    $("#SaveT").click(function () {

        var status = $("#statusddl").val();
        var owner = $("#owner").val();
        var remark = $("#remark").val();
        var test_Reference_Id = $("#testrefId").val();

        var data =
        {
            'Test_Reference_Id': test_Reference_Id,
            'Owner': owner,
            'Remarks': remark,
            'Status': status
        };

        $.ajax({
            url: '@Url.Action("UpdateTracker", "Home")',            
            type: "POST",
            contentType: 'application/json',
            dataType: 'json',
            data: data,            
            success: function (msg) {                           
            },
            error: function (XMLHttpRequest, textStatus, errorThrown) {
                alert(errorThrown);                
            }
        });

    });
});


**Controller:**
public ActionResult UpdateTracker(UpdateProxyTracker data)
        {
                SepHomeService svc = new SepHomeService();
                bool isValid = svc.UpdateData(data);
                var result = svc.GetData();
                return View("Dataview", result);
        }

Routs: routes.MapRoute( name: "Default", url: "{controller}/{action}/{id}", defaults: new { controller = "Home", action = "Index", id = UrlParameter.Optional } );

Question Here data is always Null. I Tried passing Data as JSON.stringify(data) but did not helped Do we need to add @Html.begin form tag to make ajax call Data here is getting populated before ajax call but not passed to controller Do we need to update Route to make proper Ajax call ?? Please suggest

3
is your UpdateTrackr action being hit? Are you able to debug it when making the ajax call? All is setup correctly, it's really strange.JotaBe
HI.. using debugger I can see action method being hit but model parameter valuse are null.sumit kishore

3 Answers

6
votes

Try this One, It's working for me

Don't Use

contentType: 'application/json',
dataType: 'json',

if method not a JsonResult, these things only suite for JsonResult not an ActionResult

Use Below Method.

$.ajax({
            type: "POST",
            data: {data:data},
            url: '../{ControllerName}/{MethodName}',                                                        
            success: function (response) {                           
            },
            error: function (response) {
                alert(errorThrown);                
            }
      });
3
votes

You need "hijack" the form and send data using jQ AJAX. The next sample show how make this:

// jQ
$(function() {
   $("form").submit(function(e) {
      e.preventDefault();
      e.returnValue = false;

      var status = $("#statusddl").val();
      var owner = $("#owner").val();
      var remark = $("#remark").val();
      var test_Reference_Id = $("#testrefId").val();
      // ...
   });
});

$('form').submitis short-cut to handle the submit event for any form in your page.

The calls e.preventDefault()and e.returnValue = false help to prevent that form to be submitted. Only is necessary put you AJAX.

I hope this code help you

UPDATE Plus the before solution, you need modify the data variable to the next code:

var data = {
   "data": {
      "Test_Reference_Id": test_Reference_Id,
      "Owner": owner,
      "Remarks": remark,
      "Status": status
    }
};

This is necessary, because you expect an argument called data in you controller. In addition, you attributes in JSON must use double quotes (") and not single, like you use.

0
votes
$.ajax({
            url: '@Url.Action("UpdateTracker", "Home")',            
            type: "POST",
            contentType: 'application/json',
            dataType: 'json',
            data: {data:data},/**important*/            
            success: function (msg) {                           
            },
            error: function (XMLHttpRequest, textStatus, errorThrown) {
                alert(errorThrown);                
            }
      });

maybe need a parameter name;