I am working on a simple project and want to send the JSON data to Controller
Here is my code:
var emailId = JSON.stringify(response.emails.account); // get email ID
$.ajax({
url: "/Home/GetDetails",
method: "GET",
contentType: "application/json",
dataType: "json",
data: { 'emailId': emailId },
success: function (data) {
// some logic here
}
And my Home controller is:
public JsonResult GetDetails(string emailId){
// logic here
}
The problem is JSON value of parameter emailId in controller is correct but it is in the form ""abc#gmail.com"" instead of simple "abc#gmail.com" I get the "\ .. " as an extra appended in the parameter value which I would like to avoid. How can I avoid it? Also Why is it happening? Am I missing something?
I think, instead doing this:
var emailId = JSON.stringify(response.emails.account); // get email ID
You should JSON everything in the data section of your ajax call.
Such as
data: JSON.stringify({"emailId": response.emails.account}),
Related
I have a project with areas and would like to post a view model as JSON to a controller method.
This is what I have, with performance being generated in the default area and passed to the view in area SeatSelection:
$("#addToCartButton").click(function () {
var json = #Html.Raw(Json.Encode(performance));
$.ajax({
url: 'https://#(Request.Url.Host)/SeatSelection/Home/AddToCart',
type: 'POST',
dataType: 'json',
data: json,
contentType: 'application/json; charset=utf-8',
success: function (data) {
alert(data);
}
});
});
And the action method for testing:
[System.Web.Http.Route("SeatSelection_AddToCart")]
[System.Web.Http.HttpPost]
public JsonResult AddToCart(PerformanceViewModel performance)
{
return Json(performance.Name);
}
I created the following route:
context.MapRoute(
"SeatSelection_AddToCart",
"SeatSelection/Home/AddToCart",
new { action = "AddToCart", controller = "Home", id = UrlParameter.Optional },
namespaces: new string[] { "myProject.Areas.SeatSelection.Controllers" }
);
But all I get is a internal server error 500. I also tried to use [FromBody] and setting a breakpoint to the method, but it is not invoked. I can't figure out what's wrong or missing, please help.
UPDATE
This is the json / performance:
PerformanceID=00000000-0000-0000-0000-000000000000&Name=Performance+15&StartDate=%2FDate(1360364400000)%2F&EndDate=%2FDate(1500328800000)%2F&LatestDateBookable=%2FDate(1450911600000)%2F&Organizer=Organizer+15&Location=Location+15&Availability=75&IsFull=false&IsBookable=true&HasPrice=true&BookableSeats=11&BookedSeats=94&Description=Description+of+Performance+15&Price=443
I found an error: "invalid json primitive: performanceid"
First of all, I would recommend you to use #Url.Action helper method instead of generating url like this: https://#(Request.Url.Host)/SeatSelection/Home/AddToCart.
Secondly, always validate params which comes from the browser. return Json(performance.Name) looks suspicious. What is performance will be null? This might be a problem of your internal server error 500.
If this is not a problem then try to send string instead of JSON to the server and validate and parse JSON on the server side.
You can use Url.Action method like this. I suppose SeatSelection is an area in your project.
$.ajax({
url: '#Url.Action("AddToCart", "Home", new { Area = "SeatSelection"})',
This question already has answers here:
Mvc Jquery Ajax Post returns null
(2 answers)
Closed 6 years ago.
I have an action in controller as:
public int Edit(MyViewModel viewModel)
{
// code to edit
}
And I am posting a form as:
$.post("/MyController/Edit", $("#form").serialize()).then(
function () {
$("#dialog1").dialog("close");
$("#list-grid").trigger('reloadGrid');
});
This works fine. I get the parameter in the same format as MyViewModel .
However, I need to pass one more parameter to the action. So I have changed the controller to:
public int Edit(MyViewModel viewModel, string oldValue)
{
// code to edit
}
Now, I tried following way to pass the viewModel along with the oldValue to the action using an ajax call:
var object = $("#form").serialize();
$.ajax({
url: '#Url.Action("Edit", "MyController")',
type: "POST",
contentType: // please see below
data: { viewModel: object, oldValue: oldVal},
dataType: // please see below
contentType: 'application/json',
success: function (response) {
alert("Successfully updated!");
}
});
Although I am able to get the value of oldValue, the viewModel comes as null, although it is exactly the same as that sent in the $.post(...) , when examined in the console.
If I specify the contentType as any of:
application/x-www-form-urlencoded; charset=UTF-8 or,
application/json; charset=utf-8 or,
application/json
the call fails.
I have tried without specifying the dataType, and also by specifying it as a json, but in vain.
Creating a custom class for de-serializing the json sent is not doable.
How do I solve this?
Assuming that value of oldVal is not NULL. You can try this:
var object = $("#form").serialize();
$.ajax({
url: '#Url.Action("Edit", "MyController")',
type: "POST",
contentType: application/json; charset=utf-8 // please see below
data: JSON.stringify{ viewModel: object, oldValue: oldVal},
success: function (response) {
alert("Successfully updated!");
}
});
Add dataType: "JSON", before data: { viewModel: object, oldValue: oldVal}
in my previos question Asp MVC 3 json complex object not initialize properties
My mistake was in JSON convert from Knockout and after one more time with JSON.stringify(data).
Now evering working fine with one parameter,
but I wonder about if I need send to MVC controller two or more parameters one of them is knowckout data = ko.toJSON(viewModel); variable other one is some text.
var settings = ko.toJSON(viewModel);
var parameters = JSON.stringify({ id : *"guid"*, data : settings });
$.ajax({
url: '/KioskAjax/SaveSettings/',
type: "POST",
data: parameters,
dataType: "JSON",
contentType: "application/json; charset=UTF-8",
success: function (result) {
alert('ok');
}
});
[HttpPost]
public JsonResult SaveKiosksSettings(Guid id, GlobalData data)
{
return Json(false.ToString(), JsonRequestBehavior.AllowGet);
}
In this example id is getting value, but GlobalData parameters is null again,
i think this is because I use JSON.stringify again, but how build correct JSON for controller call if I have knowckout object ?
thanks.
ko.toJSON(myObject) does a ko.toJS(myObject) and then a JSON.stringify(myObject).
So, you could choose to use ko.toJS(myObject) to get a clean copy of your data and then JSON.stringify it with your other data, as you are already doing.
I have a javascript client that is going to send json-formatted data to a set of MVC2 controllers. The client will format the json, and the controller will have no prior knowledge of how to interpret the json into any model. So, I can't cast the Controller method parameter into a known model type, I just want to grab the generic json and pass it to a factory of some sort.
My ajax call:
function SendObjectAsJSONToServer(object,url,idForResponseHTML) {
// Make a call to the server to process the object
var jsonifiedObject = JSON.stringify(object);
$.ajax({
url: url // set by caller
, dataType: 'json'
, data: jsonifiedObject
, type: 'GET'
, error: function(data) { alert('error in sendObjectAsJSONToServer:' + data); }
, success: function(data) {
alert(data.message); // Note that data is already parsed into an object
}
});
}
My MVC Controller:
public ActionResult SaveForm(string obj)
{
// Ok, try saving the object
string rc = PassJSONToSomething(obj.ToString());
string message = "{\"message\":\""+rc+"\",\"foo\":\"bar\"}";
return new ContentResult { Content = message, ContentType = "application/json" };
}
The problem is that obj is always null. Can anyone tell me how I should structure the ajax call and the controller parameter so that I get my json to the server? I'm using MVC2. This may appear to be a duplicate of some SO questions, but in my case I do not know the Model that the json maps to, so I can't use a specific model type in the controller parameter type.
Thanks very much.
Have you tried something like that?
$.ajax({
url: url // set by caller
, dataType: 'json'
, data: {obj :jsonifiedObject}
, contentType: 'application/json; charset=utf-8'
, type: 'GET'
, error: function(data) { alert('error in sendObjectAsJSONToServer:' + data); }
, success: function(data) {
alert(data.message); // Note that data is already parsed into an object
}
});
How can i post formated strings like
has<STRONG>b</STRONG>
I need to send ajax request .In my page i am using an editor , so that user can type and format. BUt ajax request failing if the string is formatted( eg: if the string have bold string .example data is shown above
var test=$('#callTranscription').val(); // contains has<STRONG>b</STRONG>
var postData = { transID: $('#callTransactionID').val(), callTranscription: test, recordID: $('#selectedRecord').val() };
$.ajax({
type: "POST",
data: postData,
url: '<%= Url.Action("SaveCallTranscription", "Search") %>',
success: function (result) {
$('#callTransactionID').val(result)
alert('success');
},
error: function (result) { alert('error'); }
});
)
Here the callTranscription contains formatted string. How can i post is safely?Is there any conersion i need to do before sending that type if data.??
You should format the string properly. Is it already formatted or are you sending raw data?
Think of URLencoding http://www.javascripter.net/faq/escape.htm