jQuery cannot deserialize json object - c#

i have this return come from here
public string Get(int id)
{
return "{\"longPachage\":{\"Id\":0}}";
}
and i Receive this return by ajax with this code
$.ajax({
type: "GET",
contentType: "application/json; charset=utf-8",
url: "http://localhost:3148/api/values/5",
success: function (data) {
alert(data);
alert(" Success ");
},
error: function (data) {
alert(" Error ");
}
})
what i can to deserialize json object and print the Id value only ?

You can use this code. It may be help to you.
You are not parse the data to get JSON in string format. So you can now use this code to get JSON data in string format.
var obj = JSON.parse(data);
$.ajax({
type: "GET",
contentType: "application/json; charset=utf-8",
url: "http://localhost:3148/api/values/5",
success: function (data) {
var obj = JSON.parse(data);
alert(obj.Id);
alert(" Success ");
},
error: function (data) {
alert(" Error ");
}
})

yes, Stephen is right.
you have to send a json result from controller.
for exa.
public JsonResult Get(int id)
{
return Json(new
{
longPachage = new { ID = 0 }
}, JsonRequestBehavior.AllowGet);
}
and in your ajax success, just retrieve that object or dataID.
$.ajax({
type: "GET",
contentType: "application/json; charset=utf-8",
url: "http://localhost:3148/api/values/5",
success: function (data) {
var dataID = data.longPachage.Id;
// Do with Your ID.
},
error: function (data) {
//Do anything for error here.
}
})

Change your method like this:
public ActionResult Get(int? id)
{
return Content("{\"longPachage\":{\"Id\":0}}");
}
And then in your jQuery:
$.getJSON("http://localhost:3148/api/values", {id:5}, function(data) {
var id = data.longPachage.Id;
alert(id)
});

Try to use JsonResult in MVC to return Json instead of building a string. JsonResult is just an abstact class of ActionResult. Modify your code in the controller as follows
Method 1:
public JsonResult GetTest(int id)
{
return this.Json(new { ID = 0 }, JsonRequestBehavior.AllowGet);
}
OR
Method 2:
Try to create a model class as LongPachage
public class LongPachage()
{
public int ID {get;set;}
}
and try to invoke into the controller method as follows
public JsonResult Get(int id)
{
LongPachage model = new LongPachage();
model.ID = 0;
return this.Json(model, JsonRequestBehavior.AllowGet);
}
OR
Method 3
Create Model class say TestModel and try to add LongPachage class as propery of this class.
public class TestModel()
{
public LongPachage LongPachage {get;set;}
}
and try to invoke into the controller method as follows
public JsonResult Get(int id)
{
TestModel model = new TestModel();
model.LongPachage .ID = 0;
return this.Json(model, JsonRequestBehavior.AllowGet);
}
and then in the view using AJAX GET wrapper try to implement as follows
$.get('#Url.Action("Get","ControllerName")', { id: "5" })
.done(function (data) {
// If you are using Method 1 or Method 2 alert will be as follows
alert(data.ID);
// If you are using method 3
alert(data.LongPachage.ID)
});

Related

ActionResult parameter is null

in my project I have a form with 2 dropdownlist and by clicking a button
it should search in DB and return list of results. this dropdownlist can also be null.
every time I click the button and sent values to my controller via ajax
it shows this error for all my values:
Object reference not set to an instance of an object.
this is my ajax code:
var ValCourse = $("#ddlCourseName").val();
var ValTeacher = $("#ddlTeachers").val();
var CurrentCourseModel = {
CourseNameID: ValCourse,
CourseTeacherID: ValTeacher,
}
var viewModel = {
"CurrentCourseModel": CurrentCourseModel
}
$.ajax({
type: "POST",
url: UrlFindCourse,
data: JSON.stringify(viewModel),
contentType: "application/json; charset=utf-8",
dataType: "json",
cache: false,
success: function (response) {
alert("Success");
}
error: function (response) {
alert("Error");
}
});
and this is my ActionResut:
public ActionResult Courses(CourseModelView viewModel)
{
try
{
CourseRepository repository = new CourseRepository();
CourseModelView model = new CourseModelView();
model.CurrentCourseModel.CourseNameID = viewModel.CurrentCourseModel.CourseNameID;
model.CurrentCourseModel.CourseTeacherID = viewModel.CurrentCourseModel.CourseTeacherID;
model.CurrentCourseModels = repository.FindCourse(model.CurrentCourseModel);
return View(model);
}
catch (Exception Err)
{
LogRepository.Logs.WriteDebug(Err, "error");
return View("~/ HttpError / 500.html");
}
}
the ajax receives all the value correctly I tested that.
but action result says all my values are null
please help me
thank you
you better create a special viewmodel for ajax
public class ViewModel
{
public int CourseNameID {get; set;}
public int CourseTeacherID {get; set;}
}
try this ajax
$.ajax({
type: "POST",
url: UrlFindCourse,
data: { viewModel:viewModel},
success: function (response) {
alert("Success");
}
error: function (response) {
alert("Error");
}
});
and fix the action too
public ActionResult Courses(ViewModel viewModel)
{
CourseModelView model = new CourseModelView{ CurrentCourseModel=new CurrentCourseModel()};
model.CurrentCourseModel.CourseNameID = viewModel.CourseNameID;
model.CurrentCourseModel.CourseTeacherID = viewModel.CourseTeacherID;
model.CurrentCourseModels = repository.FindCourse(model.CurrentCourseModel);
PS. I had to guess to write this code. Pls post CourseModelView class.

Ajax call is not passing parameter to controller method

In the Controller I added a method to perform some live data exchange into a div.
public class TextItemsController : Controller
{
//[HttpPost]
public JsonResult SpinText(string Body)
{
SpinningResult spinningResult = new SpinningResult();
spinningResult.Spintext = "This is the result text";
string jsonResult = JsonConvert.SerializeObject(spinningResult);
return Json(jsonResult);
}
}
This works in general and the result is sent back to the calling Ajax method and the div is updated with the result text as intended. So the general communication seems to work. But I never receive the input string from the Ajax call.
function doSpinning() {
//var token = $('input[name="__RequestVerificationToken"]', $('#textForm')).val();
var myData = { Body : "Hello" };
//var dataWithAntiforgeryToken = $.extend(myData, { '__RequestVerificationToken': token });
var requestData = JSON.stringify(myData);
$.ajax({
url: "/TextItems/SpinText",
type: "POST",
dataType: "json",
contentType: "application/json; charset=utf-8",
data: requestData,
success: function (data) {
var json = JSON.parse(data);
document.getElementById("PreviewText").innerHTML = json["Spintext"];
},
error: function () {
document.getElementById("PreviewText").innerHTML = "Error";
}
});
}
$("#spinButton").on('click', doSpinning);
data seems to have the correct value "{"Body":"Hello"}" before the post but string Body is always null.
Can you try to prefix your parameter with [FromBody] like this :
public JsonResult SpinText([FromBody] DtoBody Body)
And use a data transfer object so the JsonSerializer will know how to map the sent data
public class DtoBody
{
public string Body {get;set;}
}
You are posting an object with a Body property, and your method expects a string value. These don't match up, obviously, but you don't need to post an object when you only want to pass in a primitive:
$.ajax({
url: "/TextItems/SpinText",
type: "POST",
dataType: "json",
contentType: "application/json; charset=utf-8",
data: "Hello",
success: function (data) {
var json = JSON.parse(data);
document.getElementById("PreviewText").innerHTML = json["Spintext"];
},
error: function () {
document.getElementById("PreviewText").innerHTML = "Error";
}
});
Note that this is not your only problem though, as you are doing a double JSON serialization on your Action:
// serialize to JSON
string jsonResult = JsonConvert.SerializeObject(spinningResult);
//serialize the serialized object
return Json(jsonResult);
You never have to explicitly serialize to JSON, that's what the helper does for you.
Just use:
public IActionResult SpinText(string Body)
{
SpinningResult spinningResult = new SpinningResult();
spinningResult.Spintext = "This is the result text";
return Json(spinningResult);
}
And, again, you don't need to double-parse the JSON on the AJAX result:
success: function (data) {
document.getElementById("PreviewText").innerHTML = data.spintext;
},
Thanks a lot, I got it with a mix of your help.
DTO
public class SpinningInput
{
public string Title { get; set; }
public string Body { get; set; }
public string Tags { get; set; }
public string Keyword { get; set; }
}
Controller
public JsonResult SpinText([FromBody]SpinningInput spinningInput)
{
SpinningResult spinningResult = new SpinningResult();
spinningResult = Utility.Spinning.SpinText(spinningInput);
return Json(spinningResult);
}
Javascript
function doSpinning() {
const textBody = document.getElementById("Body").value;
const textTitle = document.getElementById("Title").value;
const textTags = document.getElementById("Tags").value;
const textKeyword = document.getElementById("Keyword").value;
var textData = { Title: textTitle, Body: textBody, Tags: textTags, Keyword: textKeyword };
var requestData = JSON.stringify(textData);
$.ajax({
url: "/TextItems/SpinText",
type: "POST",
dataType: "json",
contentType: "application/json; charset=utf-8",
data: requestData,
success: function (data) {
document.getElementById("PreviewText").innerHTML = data.spintext;
document.getElementById("WordCount").innerHTML = data.wordCount;
document.getElementById("KeywordDensity").innerHTML = data.keywordDensity + "%";
},
error: function () {
document.getElementById("PreviewText").innerHTML = "Error";
}
});
}
$("#spinButton").on('click', doSpinning);

pass value to controller by using ajax

I want to pass value from view to controller by using ajax.
<button onclick="addCommentByAjax()" >Save</button>
My script:
function addCommentByAjax() {
$.ajax({
type: "POST",
url: '/Survey/DoDetailSurvey',
data: {
choiceId: "1"
}
});
}
Controller:
[HttpPost]
public ActionResult DoDetailSurvey(SurveyViewModel model, string choiceId)
{
//
}
but choiceId always null
Change couple of things.
First assign an id or class to your button.Second remove inline onclick function and use ajax click function.Then specify the request type as Post.
$('#btnComment').click(function () {
var choiceId = $('#YourChoiceId').val();
$.ajax({
url: '/Survey/DoDetailSurvey',
data: { 'choiceId' : choiceId},
type: "post",
cache: false,
success: function (response) {
//do something with response
},
error: function (xhr, ajaxOptions, thrownError) {
alert('error occured');
}
});
});
Then your controller should look like this
[HttpPost]
public ActionResult DoDetailSurvey(string choiceId)
{
//
}
I don't know how you are populating your viewmodel,so I purposely removed them and shown an working example.
In case you want to pass viewmodel you should construct your data object like this:
var data = {};
data.Property1 = some val;
data.Property2 = "some val";
$.post('/Survey/DoDetailSurvey', data);
Sample structure of SurveyViewModel I assume:
public class SurveyViewModel
{
public int Property1 { get; set; }
public string Property2 { get; set; }
}
Since there are two parameter in your controller, you need to identify them both form the client side. Further, you should specify the contentType.
You spread the payload like so:
function addCommentByAjax() {
var payload = {
model: {
// whatever properties you might have
},
choiceId: 1
};
$.ajax({
type: "POST",
url: '/Survey/DoDetailSurvey',
contentType: 'application/json',
data: JSON.stringify(payLoad)
});
}
function addCommentByAjax() {
$.ajax({
type: "POST",
url: '/Survey/DoDetailSurvey?choiceId=1'
}
});
}
You can also pass like this
or for more parameters
function addCommentByAjax() {
$.ajax({
type: "POST",
url: '/Survey/DoDetailSurvey?choiceId=1&Name=Arun'
}
});
}

In ASP.NET MVC3,can I get a JsonResult in View?

Suppose I have a Action which return a JsonResult. Like below code:
public ActionResult testAction()
{
return Json(new { name="mike",age="20"});
}
It json an anonymous object and return it. Then I want to write below code in View (.cshtml) file with razor engine.
#{
JsonResult m = ///some method can help me get the JsonResult
//Then I can print the value of m
#m.Data.ToString()
}
How to do it?
why do you use json result in view? You can:
public ActionResult testAction()
{
return View(new Model{ name="mike",age="20"});
}
In your View, you can call your testAction method via an Ajax call, then access to your returned object. But as far as I know, you must return a model.
Create a Model
public class YourModel
{
public string Name { get; set; }
public int Age { get; set; }
}
A Controller :
public ActionResult testAction(string name, int age)
{
YourModel ym = new YourModel();
ym.Name = name;
ym.Age = age;
return Json(ym, JsonRequestBehavior.AllowGet);
}
Your View :
var name = "Mike";
var age = "20";
$.ajax({
url : "#Url.Action("testAction", "YourController")",
contentType : "application/json; charset=utf-8",
dataType : "json",
type : "POST",
data : JSON.stringify({name: name, age: age})
}).done(function (data) {
alert(data); // Do what you want with your object, like data.Name
})
This is a dummy example because you pass parameter from the view to the controller, then send them back to the view, but I think this sample can help you to better understand how to play with Ajax call in ASP.NET MVC3. Ajax call is asynchronous, but thank to deferred .done, you wait for the end of the server call to ensure your data object is filled
You have to use ajax to read.
$.ajax({
url: "/YourController/testAction/",
dataType: 'json',
contentType: 'application/json; charset=utf-8',
data: json,
type: 'POST',
success: function (data) {
setTimeout(function () {
//find your html element and show.
$("#ShowSomewhere").val(data.name);
}, 500);
},
error: function (jqXHR, textStatus, errorThrown) {
}
});
try use Html.Action("actionName");
this return a string

Retrieving data from Ajax POST in asp.net

I have an ajax POST like this
$(document).ready(function () {
var pcontent = document.body.innerHTML;
var url = new URI();
$.ajax({
url: url,
type: "POST",
data: { "pcontent": pcontent },
success: function (data) {
alert($(data).find(".right-panel").html());
},
complete: function () {
},
error: function (jqXHR, error, errorThrown) {
if (jqXHR.status) {
alert(jqXHR.responseText);
} else {
alert("Something went wrong");
}
}
});
return false;
});
I am little confused how i could retrieve data (pcontent) that i post here in my code behind.actually in a specific class file i need to implement this logic .
You have to create a controller action:
public class HomeController: {
// model
public class PDocument {
public string pcontent {get;set;}
}
[HttpPost]
public ActionResult SaveDocument(PDocument pcontent){
// do something
return new JsonResult() { Data = new { Success = true } };
}
}
JS:
$.ajax({
url: "Home/SaveDocument",
type: "POST",
data: { "pcontent": pcontent}
...});
Note:
You don't need to create a model on server if set
$.ajax({
url: "Home/SaveDocument",
type: "POST",
data: pcontent
});
// server side
public ActionResult SaveDocument(string pcontent){
// do some thing
}
For security reason, your html must be encoded before calling ajax
In case you new to mvc, then this is a good way to start: http://www.asp.net/mvc/tutorials/mvc-4/getting-started-with-aspnet-mvc4/adding-a-controller

Categories

Resources