User987
User987

Reputation: 3823

Posting jQuery data with special characthers

I have a quite odd problem. The problem is like this... When I try to pass a string to my controller action (.NET MVC), this one:

Small Bubble Roll 3/16" x 1400' x 12" Perforated 3/16 Bubbles 1400 Sq Ft Wrap

I checked in the console and I'm getting an server internal error 500... To make things worse I've tested whether the post will work with different kinds of titles like: "super duper amoled TV" or something like , and it works.. I suspect that the issue is because the string contains special characthers like ' and " ...

This is the post method itself:

var postData = {
    comment: $('#TextArea1').val(),
    rating: $('input[name=rating]:checked').val(),
    keyword: '@Session["Title"]'
};

First post data and now the post itself:

$.post("/Analyze/SaveWatchList", postData)
    .done(function (response) {
        // do something with the response here...
    });
});

And now the Controller action itself:

[ActionName("SaveWatchList")]
[HttpPost]
public ActionResult SaveWatchList(string comment, string rating, string keyword)
{

}

With the title itself that I've shown above, action doesn't gets triggered at all.. Instead I simply get internal server error 500 in console...

How could I fix this ?

Upvotes: 0

Views: 61

Answers (1)

Sajal
Sajal

Reputation: 4401

You could serialize the postData and expect a request object at the action which can further be de-serialized to obtain individual properties.

Model:

public class ExampleRequest {
  public string comment {get; set;};
  public string rating {get; set;};
  public string keyword {get; set;};
}

Controller Action:

[ActionName("SaveWatchList")]
[HttpPost]
public ActionResult SaveWatchList(ExampleRequest req)
{ 
  var comment = req.comment;
  var rating = req.rating;
  var keyword = req.keyword;
}

Update:

Json object:

var postData = {
      comment: $('#TextArea1').val(),
      rating: $('input[name=rating]:checked').val(),
      keyword: '@Session["Title"]'
};

Upvotes: 1

Related Questions