0

I am doing a simple AJAX POST from CSHTML. In the post, I am passing a string.

 $.ajax({
      type: "POST",
      url: '@Url.Action("Test","Controller"',
      contentType: "application/json; charset=utf-8",
      data: JSON.stringify({ pt: 'testString' }),
      cache: false,
      success: function(data) {
      }
 });

I want to get this value in controller as follows -

[HttpPost]
public JsonResult Test()
{
       var pt = string.empty;
       TryUpdateModel(pt);
       // Do some processing and return a value
       return Json(true);
}

But always my pt comes as empty. Also please do give me solution with works with value types as well.

  • 1
    Your controller code doesn't make sense. You are not using `planType` and declaring a new `pt` instead! The parameter of your action should be named `pt` – Delphi.Boy Feb 10 '15 at 20:09
  • You don't have a model. What would be the point of `TryUpdateModel` You method needs to be `public ContentResult GetPlansData(string pt)` and pt will be the value you posted which is "teststring" –  Feb 10 '15 at 21:08
  • I updated my question, my questions main intent is on how to get a string (and also values types) using TryUpdateModel(). – Raghu Reddy Feb 11 '15 at 04:03

2 Answers2

1

try this:

[HttpPost]
public JsonResult Test()
{
       var pt = Request.Params["pt"]
       // Do some processing and return a value
       return Json(true);
}

OR

class PtModel { public string pt { get; set; } }
[HttpPost]
public JsonResult Test()
{
        var ptModel = new PtModel();
        TryUpdateModel(ptModel);
        var language = ptModel.pt;

       // Do some processing and return a value
       return Json(true);
}

TryUpdateModel correct works only for objects with properties

DrakonHaSh
  • 831
  • 6
  • 7
0

The method for the controller should be

[HttpPost]
public ActionResult Test(string pt)
{
   TryUpdateModel(pt);
   // Do some processing and return a value
   return Json(true);
}
Huy Hoang Pham
  • 4,107
  • 1
  • 16
  • 28