How to return JSON with ASP.NET & jQuery
You're not far; you need to do something like this:
[WebMethod]
public static string GetProducts()
{
// instantiate a serializer
JavaScriptSerializer TheSerializer = new JavaScriptSerializer();
//optional: you can create your own custom converter
TheSerializer.RegisterConverters(new JavaScriptConverter[] {new MyCustomJson()});
var products = context.GetProducts().ToList();
var TheJson = TheSerializer.Serialize(products);
return TheJson;
}
You can reduce this code further but I left it like that for clarity. In fact, you could even write this:
return context.GetProducts().ToList();
and this would return a json string. I prefer to be more explicit because I use custom converters. There's also Json.net but the framework's JavaScriptSerializer
works just fine out of the box.
Return Json object from Asp.net webMethod to Ajax call
Include using Newtonsoft.Json;
CS
public string CheckDetails(string param1, string param2)
{
var chk = new check
{
subject = "hello! " +param1 ,
description = param2 +" Years Old"
};
return JsonConvert.SerializeObject(chk);
}
public class check
{
public string subject { get; set; }
public string description { get; set; }
}
HTML
<div>
<input type="text" name="name" id="txtname"/>
<input type="text" name="age" id="txtage"/>
<input type="button" id="btnSubmit" value="details"/>
</div>
Jquery
$(function () {
$('#btnSubmit').on('click', function () {
var options = {
type: "POST",
url: '/Ajax/CheckDetails/',
data: '{param1:"' + $('#txtname').val() + '",param2:"' + $('#txtage').val() + '"}',
async: false,
cache: false,
dataType: "json",
contentType: "application/json; charset=utf-8",
success: function (response) {
if (response != null && response.d != null) {
var data = response.d;
alert(typeof (data)); //it comes out to be string
//we need to parse it to JSON
data = $.parseJSON(data);
alert(data.subject);
alert(data.description);
}
}
};
$.ajax(options);
});
});
get JSON object using jquery with ajax call from controller to view
Thanks for getting involved, after spending some time with your suggestions I managed to find a way to work around:
newObj.Add(bookSeat.Number.ToString());
newObj.Add(bookSeat.Result);
return Json(newObj.ToArray());
I am returning an array now and I access it in view as follows:
$("#test").append(data1[1]);
Also, I analysed the data that is being received back, so I did the following:
$("#test").append(data1["result"]);
and now i get the expected string
Return JSON with ajax is giving me blank page with return parameters
What you did is just a form submit instead of using ajax. Why it return json string that is because you return json string in your backend code(return Json(new { success = true, message = messagebad }, new Newtonsoft.Json.JsonSerializerSettings());
).
I saw you use jquery.unobtrusive-ajax.js
in your code, also you create a js function with ajax. Actually, you just need to choose one of the two ways to achieve your requrement.
Here is the correct way of using jquery.unobtrusive-ajax.js
:
Note:
1.If you use asp.net core, it contains jquery.js
in _Layout.cshtml by default. So when you use @section Scripts{}
, no need add the jquery.js
again. If your _Layout.cshtml does not contain jquery.js
, you need add this js file before jquery.unobtrusive-ajax.js
:
<script src="~/lib/jquery/dist/jquery.js"></script>
<script src="~/lib/ajax/jquery.unobtrusive-ajax.js"></script>
2.You need specific data-ajax-update
to tell the elements where need to be updated with the AJAX result.
More supported data attributes for jquery.unobtrusive-ajax.js
you can refer to here.
View:
@model Vote
@addTagHelper*, Microsoft.AspNetCore.Mvc.TagHelpers
@{
ViewData["Title"] = "sssss";
}
<div id="result"> //add this div...
//add this...
<form asp-action="VoteUp" asp-controller="Home" method="POST" data-ajax-update="#result" data-ajax="true">
<div class="form-group"> </div>
<div class="input-group-button">
<button name="plus" class="btn btn-dark" value="1">+</button>
@Model.Votes
<input hidden asp-for="Votes" /> //add this....
<button name="minus" class="btn btn-dark" value="-1">-</button>
</div>
</form>
</div>
@section scripts{
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery-ajax-unobtrusive/3.2.6/jquery.unobtrusive-ajax.js" integrity="sha256-v2nySZafnswY87um3ymbg7p9f766IQspC5oqaqZVX2c=" crossorigin="anonymous"></script>
}
Controller:
Note: You can see that I add a hidden input for Votes
in form, that is because only input or select type of element can be post to backend. The reason for why I want to get Votes
value is because your code always create a new instance for Vote, the value will always plus start with 0
.
public IActionResult Privacy()
{
Vote vote = new Vote();
vote.Votes = 0;
return View(vote);
}
[HttpPost]
public ActionResult VoteUp(string plus, string minus)
{
Vote vote = new Vote();
vote.Votes = int.Parse(Request.Form["Votes"]);
if (plus == null)
{
vote.Votes = vote.Votes - 1;
}
else if ((minus == null))
{
vote.Votes = vote.Votes + 1;
}
else { }
return PartialView("Privacy", vote);
}
Result:
jQuery ajax is showing json from Asp.Net Core response
This is the default form submit behavior, you should stop it if you want it submit with ajax.
<form asp-controller="city" asp-action="create" id="cityCreateFrom" method="post" onsubmit="return CreateResource(event, 'cityCreateFrom', 'City created successfully.')">
<partial name="_CityInfo.cshtml" />
</form>
function CreateResource(event, formid, successfulmessage) {
event.preventDefault()
//...
}
Return JSON using AJAX in ASP.NET CORE form
Firstly,you need to add jquery.unobtrusive-ajax.min.js
or 'jquery.unobtrusive-ajax.js'.If you want to post file,you need to add enctype="multipart/form-data"
.Here is a demo(It will trigger onBegin
and onComplete
):
View:
<form asp-controller="Home" asp-action="Upload" data-ajax="true" data-ajax-begin="onBegin"
data-ajax-complete="onComplete" data-ajax-failure="onFailure" enctype="multipart/form-data">
<input type="submit" value="submit"/>
</form>
js:
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery-ajax-unobtrusive/3.2.6/jquery.unobtrusive-ajax.min.js"></script>
<script>
function onFailure(result) {
alert("onFailure ");
};
function onComplete(result) {
alert("onComplete " + result.responseJSON.test + " " + result.responseJSON.test2 + " " + result.responseJSON.test3);
};
function onSuccess(result) {
alert("onSuccess " + result.responseJSON.test + " " + result.responseJSON.test2 + " " + result.responseJSON.test3);
};
function onBegin(result) {
alert("onBegin ");
};
</script>
Model:
public class UploadViewModel
{
public IFormFile File { get; set; }
}
result:
jquery.POST to MVC controller to return JSON
I think your model's data is not set thus you get null values on Chrome.
If your javascript does not have a typo (and that you only made a typo when creating the question, then try this in your method myCtrlAction
;
First try create getters and setters for your fields in myModel. Then;
replace;
errorMessage += "</ul>";
return Json(new myModel { Name = errorMessage }); //just for now
with this;
myModel myMODTest= new myModel();
myMODTest.setID(1111);
myMODTest.setName("testName");
myMODTest.setDays({1,2,3});
return Json(myMODTest); //just for now
See if you get on your browser the following;
{ID: "1111", Name: "testName", Days: "{1,2,3}"}
How to return Json object on Web API Controller
If you create yourself a new HttpContent class for delivering JSON, like...
public class JsonContent : HttpContent {
private readonly MemoryStream _Stream = new MemoryStream();
public JsonContent(object value) {
Headers.ContentType = new MediaTypeHeaderValue("application/json");
var jw = new JsonTextWriter( new StreamWriter(_Stream));
jw.Formatting = Formatting.Indented;
var serializer = new JsonSerializer();
serializer.Serialize(jw, value);
jw.Flush();
_Stream.Position = 0;
}
protected override Task SerializeToStreamAsync(Stream stream, TransportContext context) {
return _Stream.CopyToAsync(stream);
}
protected override bool TryComputeLength(out long length) {
length = _Stream.Length;
return true;
}
}
Then you can do,
public HttpResponseMessage Get() {
return new HttpResponseMessage() {
Content = new JsonContent(new
{
Success = true, //error
Message = "Success" //return exception
})
};
}
just like you do with JsonResult.
Related Topics
How to Use Jwt in MVC Application for Authentication and Authorization
ASP.NET Page Is Not Loading CSS Styles
What Is a Dynamic Language, and Why Doesn't C# Qualify
Disable JavaScript Error in Webbrowser Control
C# Rsa Public Key Output Not Correct
How Does the .Tostring() Method Work
ASP.NET Core 2.0 Authentication Middleware
Soap Client in .Net - References or Examples
When Do We Need to Set Processstartinfo.Useshellexecute to True
Cross Platform (PHP to C# .Net) Encryption/Decryption with Rijndael
Load CSS Dynamically in ASP.NET
In Ruby, What Is the Equivalent to an Interface in C#
How Would You Code an Efficient Circular Buffer in Java or C#
How to Detect Keypress While Not Focused
C# Httpwebrequest Command to Get Directory Listing
Why Does It Appear That My Random Number Generator Isn't Random in C#