When I using a literal stringified JSON object, all works as expected
Index.cshtml (with literal ajax string $.ajax WORKS)
var searchObject = new Object();
searchObject.Thing1 = '42';
searchObject.Thing2 = '43';
searchObject.Thing3 = '44';
var searchSerialized = JSON.stringify(searchObject);
alert(searchSerialized);
$.ajax(
{
url: '/api/auditApi',
type: "Post",
contentType: "application/json; charset=utf-8",
data: '{\'Thing1\':\'42\',\'Thing2\':\'43\',\'Thing3\':\'44\'}',
dataType: 'json',
success: function (result) {
$(".kendoAudit").data("kendoGrid").dataSource = new kendo.data.DataSource({ data: result });
$(".kendoAudit").data("kendoGrid").dataSource.read();
$(".kendoAudit").data("kendoGrid").refresh();
},
error: function (xhr, ajaxOptions, thrownError) {
alert('Status: ' + xhr.status + ', Error Thrown: ' + thrownError);
}
});
However, when I use a serialized object created inline, it get null passed in to the post handler
Index.cshtml (with object created inline and passed to $.ajax FAILS)
var searchObject = new Object();
searchObject.Thing1 = '42';
searchObject.Thing2 = '43';
searchObject.Thing3 = '44';
var searchSerialized = JSON.stringify(searchObject);
alert(searchSerialized);
$.ajax(
{
url: '/api/auditApi',
type: "Post",
contentType: "application/json; charset=utf-8",
data: searchSerialized, //I have tried concatenating with + '' also
dataType: 'json',
success: function (result) {
$(".kendoAudit").data("kendoGrid").dataSource = new kendo.data.DataSource({ data: result });
$(".kendoAudit").data("kendoGrid").dataSource.read();
$(".kendoAudit").data("kendoGrid").refresh();
},
error: function (xhr, ajaxOptions, thrownError) {
alert('Status: ' + xhr.status + ', Error Thrown: ' + thrownError);
}
});
Controller
public HttpResponseMessage Post([FromBody]string value)
{
try
{
var results = JsonConvert.DeserializeObject<dynamic>(value);
}
catch (Exception ex)
{
// throws because value is null.
}
}
I'm sure there's something abundantly obvious I'm missing in the conversion here.
The debug line: alert(searchSerialized); displays what I'm expecting
You can directly get the data into model.
When serialized object is posted (which is no more string) MVC automatically bind it to the proper model.
Now change your action method something like this.
public class SearchObject
{
public int Thing1 { get; set; }
public int Thing2 { get; set; }
public int Thing3 { get; set; }
}
[HttpPost]
public ActionResult Test(SearchObject searchObject)
{
return View();
}
Related
I am learning C# MVC using dotnetfiddle web to write code.
I have created a new project with the default code of dotnetfiddle for MVC type, but I want to display the question in the alert instead of the answer.
I want to know how to pass parameters to the controller from the view.
This is the ajax method:
$.ajax({
url: '#Url.RouteUrl(new{ action="GetAnswer", controller="Home"})',
data: JSON.stringify({Answer: '', Question: $('#Question').val()}),
type: 'POST',
dataType: 'json',
contentType: "application/json; charset=utf-8",
success: function(resp) {
openAlert(resp.result);
},
error: function(XMLHttpRequest, textStatus, errorThrown) {
openAlert("ERROR: " + errorThrown);
}
});
And this is the controller method:
[HttpPost]
public JsonResult GetAnswer(string question)
{
int index = _rnd.Next(_db.Count);
var answer = _db[index];
return Json(new { result = question});
}
You can check and test the code here: dotnetfiddle (Edit: it will be a good answer if it works here)
These code changes will work for you. If you wanna verify check the fiddle. DotNetFiddle
Client side Changes
$.ajax({
url: '#Url.RouteUrl(new{ action="GetAnswer", controller="Home"})',
data: {"Answer": '', "Question": $('#Question').val()},
type: 'POST',
success: function(resp) {
openAlert(resp.Question);
},
error: function(XMLHttpRequest, textStatus, errorThrown) {
openAlert("ERROR: " + errorThrown);
}
});
Server Side Changes
[HttpPost]
public JsonResult GetAnswer(SampleViewModel model)
{
int index = _rnd.Next(_db.Count);
var answer = _db[index];
return Json(model);
}
This is the method I used to pass parameters to controller
First, assign the parameter you want to pass to a variable with the value from the
input id as stated in your dotnetfiddle
var questionParam = $("#Question").val();
Then for passing it to AJAX, I think your method is already correct, this is how I do it
$.ajax({
url: '/Home/GetAnswer?question=' + questionParam ,
type: 'POST',
dataType: 'json',
contentType: "application/json; charset=utf-8",
success: function(resp) {
openAlert(resp.result);
},
error: function(XMLHttpRequest, textStatus, errorThrown) {
openAlert("ERROR: " + errorThrown);
}
});
This method works for me in my project, if the value is a string I think you don't need to stringify the value.
I'm still a beginner as well so maybe my method is wrong or not the best way to do it, I hope it helps you.
You are getting the value of the question in the action because your action has got a single parameter string question in there.
What you need to do is:
Send a json object from the view
In the action user a model with two properties (Answer and Question) to get the value sent by the view
Then in the action you decide what data you need to send to view
View:
Send JSON object to action:
JSON.stringify({Answer: '', Question: $('#Question').val()})
When you get the data returned from controller:
openAlert(resp.Answer);
Controller:
public JsonResult GetAnswer(MyQA model)
{
// model.Answer
// model.Question
// Your business logic goes here
return Json(new { result = model});
}
Here is the MyQA class:
public class MyQA
{
public string Answer { get; set; }
public string Question{ get; set; }
}
dotnetfiddle had a problem with this line: contentType: "application/json; charset=utf-8",
change script to :
$('.submit').click(function() {
if ($('form').valid()) {
$.ajax({
url: '#Url.Action("GetAnswer", "Home")',
data: {
Answer: '',
Question: $('#Question').val()
},
type: 'POST',
dataType: 'json',
success: function(resp) {
openAlert('Answer :' + resp.Answer + ' -----Question : ' + resp.Question);
},
error: function(XMLHttpRequest, textStatus, errorThrown) {
openAlert("ERROR: " + textStatus);
}
});
} else {
closeAlert();
}
});
change action GetAnswer to :
[HttpPost]
public JsonResult GetAnswer(string Answer,string Question)
{
int index = _rnd.Next(_db.Count);
var answer = _db[index];
return Json(new {Answer = answer,Question = Question});
}
[HttpPost]
[Route("mapchanged")]
public ActionResult mapchanged(string latitud, string longitud)
{
Session["Latitude"] = latitud;
Session["Longitude"] = longitud;
return RedirectToAction("search?what=&by=bnm");
}
$.ajax({
type: "POST",
async: false,
url: url, // '#Url.Action("mapchanged")',
data: {
latitud: map.getCenter().lat(),
longitud: map.getCenter().lng()
},
dataType: "json",
contentType: 'application/json; charset=utf-8',
cache: false,
success: function(data) {
alert('Success');
},
error: function(err) {
alert('error = ' + err.status);
}
});
The above code is not working - it's giving error 404. Also tried var url = '"Home/mapchanged/"' but it's also not working. The ajax code is in map.js file.
Do you have a view for that action? Plus it's an ajax post, you can't redirect to another action while doing ajax post. Try to return json from that action and see if it works.
return Json(new { true }, JsonRequestBehavior.AllowGet);
I tried to reproduce source code. It had some issues with current code.
Missed configure for Route attribute at RouteConfig class, without this configure [Route] annotation/attribute not work.
routes.MapMvcAttributeRoutes()
In ajax call did not use JSON.stringify for data
var data = {
latitud: map.getCenter().lat(),
longitud: map.getCenter().lng()
};
$.ajax({
type: "POST",
async: false,
url: '#Url.Action("mapchanged")',
data: JSON.stringify(data),
dataType: "json",
contentType: 'application/json; charset=utf-8',
cache: false,
success: function (data) {
alert('Success');
window.location.href = data.url;
},
error: function (err) {
alert('error = ' + err.status);
}
});
You should return Json object with url property instead of RedirectToAction
[HttpPost]
[Route("mapchanged")]
public ActionResult mapchanged(LongLat obj)
{
Session["Latitude"] = obj.latitud;
Session["Longitude"] = obj.longitud;
//return RedirectToAction("search?what=&by=bnm");
return Json(new {url = "search?what=&by=bnm"});
}
public class LongLat
{
public double latitud { get; set; }
public double longitud { get; set; }
}
I have an AJAX code where I am trying to send some data to a method within C# code-behind
I've tried to send them either using text data type and json data type, but neither of them are working with me.
when I use json type, it returns me the following error:
Internal Server Error
and when using text me
thod, there is no error appear and the code comes through the success function, but the actually the data is never sent to the method of the code-behind class
this is the ajax code using json type:
function searchClicked(sCriterion) {
$.ajax({
type: "POST",
url: "TokenRegistration.aspx/GetSearchCritetrion",
data: "{creiterion : " + sCriterion + " }",
contentType: "application/json; charset=utf-8",
dataType: "json",
error: function (XMLHttpRequest, textStatus, errorThrown) {
alert("Request: " + XMLHttpRequest.toString() + "\n\nStatus: " + textStatus + "\n\nError: " + errorThrown);
},
success: function (result) {
alert("We returned: " + result);
}
And this is the ajax code using the text format:
function searchClicked(sCriterion) {
$.ajax({
type: "POST",
url: "TokenRegistration.aspx/GetSearchCritetrion",
data: sCriterion,
contentType: "application/text; charset=utf-8",
dataType: "text",
error: function (XMLHttpRequest, textStatus, errorThrown) {
alert("Request: " + XMLHttpRequest.toString() + "\n\nStatus: " + textStatus + "\n\nError: " + errorThrown);
},
success: function (result) {
alert("We returned: " + result);
}
Also here is the my code-behind method that the data should be sent to:
[WebMethod]
[ScriptMethod(ResponseFormat = ResponseFormat.Json)]
public void GetSearchCritetrion(object selectedItem)
{
var json = new JavaScriptSerializer();
var data = json.Deserialize<Dictionary<string, Dictionary<string, string>>[]>(selectedItem.ToString());
}
I've used the exact same ajax code in another project and it works perfectly, but here i'm not getting where the error is, so any suggestions please?
see if this works
instead of sending object try to pass as string
data: JSON.stringify({selectedItem : sCriterion }),
code behind
public void GetSearchCritetrion(string selectedItem)
Here is a really simple example that posts JSON to a controller method, which converts this into an object and then returns a response.
HTML:
<button id="go" class="btn">Go</button>
JS:
var obj = { foo: 123, bar: "abc " };
$('#go').click(function () {
$.ajax({
contentType: 'application/json; charset=utf-8',
dataType: 'json',
type: 'POST',
url: '/Test/TestJson',
data: JSON.stringify(obj),
success: function (response) {
alert(response.result)
},
failure: function (response) {
alert('fail');
}
});
});
Controller:
public class TestController : Controller
{
[OutputCache(Location = OutputCacheLocation.None)]
public JsonResult TestJson(TestClass tc)
{
return Json(new { result = "foo=" + tc.foo + " bar=" + tc.bar }, JsonRequestBehavior.AllowGet);
}
public class TestClass
{
public int foo { get; set; }
public string bar { get; set; }
}
}
I think this help you.
class Item
{
public int id { get; set; }
}
[WebMethod]
public static void GetSearchCritetrion(Item selectedItem)
{
//ToDo: selectedItem.id
}
I am trying to submit a object from a form to my mvc controller.
here is the js:
<script>
function submitForm() {
var usersRoles = new Array;
jQuery("#dualSelectRoles2 option").each(function () {
usersRoles.push(jQuery(this).val());
});
var model = new Object();
model.user = jQuery('#selectUser').val();
model.roleslist = usersRoles;
console.log('model: ' + 'user: ' + model.user + 'roles: ' + model.roleslist);
console.log('JSON: ' + JSON.stringify(model));
jQuery.ajax({
type: "POST",
url: "#Url.Action("
AddUser ")",
dataType: "json",
//data: { model: JSON.stringify(usersRoles) },
data: {
model: JSON.stringify(model)
},
success: function (data) {
alert(data);
},
failure: function (errMsg) {
alert(errMsg);
}
});
}
now that fetches al the necessary info and builds the object "model" and then posts it to the controller.
Here is my view model:
//for receiving from form
public class submitUserRolesViewModel
{
public string userId { get; set; }
public List<String> rolesList { get; set; }
}
Here is my controller:
//Post/ Roles/AddUser
[HttpPost]
public ActionResult AddUser(StrsubmitUserRolesViewModel model)
{
if (model != null)
{
return Json("Success");
}
else
{
return Json("An Error Has occoured");
}
}
How can I receive a json object in the controller? Now currently my model is null when a post is executed by the jquery. This means that it is not binding correctly. I am sure there is just something small wrong here.
Could you please point out where I am going wrong.
jQuery.ajax({
type: "POST",
url: "#Url.Action("AddUser")",
contentType: "application/json",
data: JSON.stringify(model),
success: function (data) { alert(data); },
error: function (errMsg) {
alert(errMsg);
}
});
I slightly modified you JQuery and it is working as expected now -
<script src="~/Scripts/jquery-1.10.2.min.js"></script>
<script>
function submitForm() {
var roles = ["role1", "role2", "role3"];
var rolesArray = jQuery.makeArray(roles);
var model = new Object();
model.userId = 1;
model.rolesList = rolesArray;
jQuery.ajax({
type: "POST",
url: "#Url.Action("AddUser")",
dataType: "json",
contentType: "application/json; charset=utf-8",
data: JSON.stringify(model),
success: function (data) { alert(data); },
failure: function (errMsg) {
alert(errMsg);
}
});
}
</script>
<input type="button" value="Click" onclick="submitForm()"/>
Output -
I am calling this action of api from client. The client code also see below.
API Action:
public class StudentTestController : ApiController
{
[HttpPost]
public HttpResponseMessage GetLessonInfo(int request)
{
HttpResponseMessage result = null;
result = Request.CreateResponse(HttpStatusCode.OK,StudentTest.GetLessonInfo(request));
return result;
}
}
JavaScript client script:
function SendRequest() {
var url = "http://localhost:1938/api/StudentTest/GetLessonInfo";
var data1 = "request=293";
$.ajax({
type: 'POST',
url: url,
data: data1,
contentType: 'application/json; charset=utf-8',
dataType: 'jsonp',
success: function (data) {
$('#txtResponce').val(JSON.stringify(data.Data));
},
error: function (xhr, status, error) {
var errorText = xhr.status + "\r\n" + status + "\r\n" + error;
$('#txtResponce').val(errorText);
}
});
}
When i am trying to call Action with the above snippet it will not calling the controller action. How to solve this?
Pavan.
Have you tried this instead:
var url = "/api/StudentTest/GetLessonInfo";
var data1 = "293";
Maybe "request=293" can be considered as a string and not the "int" expected as parameter.
And since the int parameter is not nullable, maybe it's giving you a Bad Request response.
Check with Fiddler what is being sent to the server.