how to return JSON with MVC Controller - asp.net-mvc

I am calling my controller method using .ajax. my controller method call web service which returns dictionary.
now i need to return this and populate dropdown list. i am trying with return JSON and need to populate using success (response)
I am using MVC 1.0
$.ajax(
{
url: 'LookupValue/',
data: { 'sLookupIds': selectedtext },
datatype: "json",
traditional: true,
success: function (data) {
alert(data.value);
}
});
thanks in advance.

In controller
public JsonResult LookupValue(String sLookupIds)
{
SelectList olist = new SelectList(oDict, "key","value");
return Json(olist);
}
In view
$.ajax(
{
url: 'LookupValue/',
data: { 'sLookupIds': selectedtext },
datatype: "json",
traditional: true,
success: function (data) {
$.each(data, function (index, val) {
$('#lookup')
.append($("<option></option>")
.attr("value", val.Value)
.text(val.Text));
//ddHTML = ddHTML + "<option value='" + val.Value + "'>'" + val.Texts + "'</option>";
});
}
});

In your Action in your Controller:
return Json(data);
Where data is your object that you want serialiazed to JSON.
If you want to use Json.NET, just override the Json method.

Related

How to send json object to the Controller Action method in MVC 4

I am trying to send my userid and password to my login Controller Action method.
//Login button click code
$("#btnLogin").click(function () {
var userCrdential = {
UserName: $("inputEmail3").val(),
Password: $("inputPassword3").val()
};
$.ajax({
type: "POST",
url: "/Home/Login",
content: "application/json; charset=utf-8",
dataType: "json",
data: userCrdential,
success: function (res) {
// alert("data is posted successfully");
if (res.success == true)
alert("data is posted successfully");
else {
// alert("Something went wrong. Please retry!");
}
},
error: function (xhr, textStatus, errorThrown) {
alert(xhr.statusMessage);
}
});
});
and in my home Controller I have login Action method
[HttpPost]
[ActionName("Login")]
public ActionResult Login(User userCrdential)
{
string userIdtest = userCrdential.UserName;
string userPasswordtest = userCrdential.Password;
var result=false;
if (userIdtest != null && userPasswordtest != null)
{
result = true;
}
else
{
result = false;
}
return Json(result);
//return RedirectToAction("Index");
}
but my action method is not invoking...
You need to change content to contentType and call JSON.stringify on your data:
$.ajax({
type: "POST",
url: "/Home/Login",
contentType: "application/json; charset=utf-8",
dataType: "json",
data: JSON.stringify(userCrdential),
...
});
See jQuery.ajax
Just change it from:
var userCrdential = {
UserName: $("inputEmail3").val(),
Password: $("inputPassword3").val()
};
to:
var userCrdential = "UserName=" + $("inputEmail3").val() + "&Password=" + $("inputPassword3").val();
all other things is ok in your code, but make sure your controller parameter having the same parameters passing here i.e. UserName and Password.
however you need to check user input before calling ajax.
You should never hard-code URLs in MVC.
Instead use #Url.Action.
url: ('#Url.Action("Login", "Home")',
userCrdential needs to be JSON encoded:
JSON.stringify(userCrdential)
Also, for the same of your sanity, please use the fail method.
$.ajax("url")
.done(function() {
alert("success");
})
.fail(function() {
alert("error");
})
One last note, success is deprecated as of jQuery 1.8; you should use done instead.

How to bind IDictionary data in a Webgrid

i have a ajax call which calls the ControllerName "Floor" and ActionMethod "GetHotelingList".i have a Dropdown list facility. when i select option from the Dropdownlist list the control goes to ajax call.based on selection value, the Webgrid must be displayed. #grdHoteling is Webgrid id.
$.ajax({
type: 'GET',
url: '/Floor/GetHotelingList',
cache: false,
contentType: 'application/html; charset=utf-8',
dataType: 'html',
data: { floorId: floorId },
success: function (data) {
debugger;
$("#grdHoteling").val(data);
//debugger;
//$("#grdHoteling").html(data);
},
complete: function () {
},
error: function () {
if (facilityName.indexOf('-') != -1) {
$('#floor').empty();
return;
}
else
alert("Error in generating hoteling information");
}
});
Here is the ActionMethod GetHotelingList value is paased floorId for some fileration.
public List<IDictionary> GetHotelingList(int floorId)
{
var model = new List<IDictionary>();
using (var context = new FloorContext())
{
try
{
model = ListHotelingByFloorId(context, floorId);
}
catch (Exception ex)
{
}
}
return model;}
On Success of the ajax call, when i check through debugger am getting data as "System.Collections.Generic.List`1[System.Collections.IDictionary]" and child cannot be evaluated.
kindly help...!
thanks...!

Send data from js to controller

I have this ajax:
function sendData() {
var question = (document.getElementById('question').value).toString();
var c = (document.getElementById('c').value).toString();
$.ajax({
url: '/Home/InsertData',
type: 'POST',
data: {question:question, c:c},
// data: {},
dataType: 'json',
contentType: 'application/json; charset=utf-8',
success: function () {
alert('suc');
},
error: function (error) {
alert('error');
}
});
}
in my HomeController, I have the function:
[HttpPost]
public void InsertData(string question, string c)
//public void InsertData()
{
this.insertDataToCustomers(question, c);
}
when I run it, I got an error of:
POST http://localhost:2124/Home/InsertData 500 (Internal Server Error)
If I didn't ask for input values in InsertData function and didn't send data in the ajax, it works. why can't I send data to InsertData function?
p.s. There are values in question and c
thank you!
Remove this:
contentType: 'application/json; charset=utf-8',
You are not sending any JSON to the server, so this is an incorrect content type for the request. You are sending a application/x-www-form-urlencoded request.
So:
function sendData() {
var question = $('#question').val();
var c = $('#c').val();
$.ajax({
url: '/Home/InsertData',
type: 'POST',
data: { question: question, c: c },
success: function () {
alert('suc');
},
error: function (error) {
alert('error');
}
});
}
Another problem with your code is that you indicated dataType: 'json' which means that you expect the server to return JSON but your controller action doesn't return anything. It's just a void method. In ASP.NET MVC controller actions should return ActionResults. So if you want to return some JSON for example to indicate the status of the operation you could have this:
[HttpPost]
public ActionResult InsertData(string question, string c)
{
this.insertDataToCustomers(question, c);
return Json(new { success = true });
}
Of course you could return an arbitrary object which will be JSON serialized and you will be able to access it in your success AJAX callback.

Controller Action cannot be called from $.Ajax javascript

In MVC, I have written an action in the controller for getting values. The action is as follows..
public void poolshapepdf(List<String> values)
{
...
}
To pass the parameter values to the controller action i pass the values from javascript..
the code is the below,
$.ajax({
type: 'POST',
url: rootDir + "IngroundCalculation/poolshapepdf",
data: { values: collectionPSElmt },
traditional: true,
});
Here collectionPSElmt is an array.
collectionPSElmt[index] = poolshapeValue[index] + "-" + psFeet[index] + "-" + psInch[index];
Here the issue is the controller action cannot be called from the javascript $.Ajax(..).
How do I fix this issue?
You calling the controller by POST and JSON data:
[HttpPost]
public JsonResult poolshapepdf(DataClass[] items)
{
}
Now, make a proper call to your url.
specify the data type as json and always go for success function.
using that you can easily crack the report.
$.ajax({
url: '#Url.Action("poolshapepdf", "IngroundCalculation")',
type: "POST",
dataType: 'json',
data: collectionPSElmt ,
contentType: "application/json; charset=utf-8",
success: function (result) {
alert("Working..");
}
});
And at Controller Side,
[HttpPost]
public JsonResult poolshapepdf(DataClass[] items)
{
// Your Code here....
}

How can I RedirectToAction within $.ajax callback?

I use $.ajax() to poll an action method every 5 seconds as follows:
$.ajax({
type: 'GET', url: '/MyController/IsReady/1',
dataType: 'json', success: function (xhr_data) {
if (xhr_data.active == 'pending') {
setTimeout(function () { ajaxRequest(); }, 5000);
}
}
});
and the ActionResult action:
public ActionResult IsReady(int id)
{
if(true)
{
return RedirectToAction("AnotherAction");
}
return Json("pending");
}
I had to change the action return type to ActionResult in order to use RedirectToAction (originally it was JsonResult and I was returning Json(new { active = 'active' };), but it looks to have trouble redirecting and rendering the new View from within the $.ajax() success callback. I need to redirect to "AnotherAction" from within this polling ajax postback. Firebug's response is the View from "AnotherAction", but it's not rendering.
You need to consume the result of your ajax request and use that to run javascript to manually update window.location yourself. For example, something like:
// Your ajax callback:
function(result) {
if (result.redirectUrl != null) {
window.location = result.redirectUrl;
}
}
Where "result" is the argument passed to you by jQuery's ajax method after completion of the ajax request. (And to generate the URL itself, use UrlHelper.GenerateUrl, which is an MVC helper that creates URLs based off of actions/controllers/etc.)
I know this is a super old article but after scouring the web this was still the top answer on Google, and I ended up using a different solution. If you want to use a pure RedirectToAction this works as well. The RedirectToAction response contains the complete markup for the view.
C#:
return RedirectToAction("Action", "Controller", new { myRouteValue = foo});
JS:
$.ajax({
type: "POST",
url: "./PostController/PostAction",
data: data,
contentType: "application/json; charset=utf-8",
dataType: "json",
complete: function (result) {
if (result.responseText) {
$('body').html(result.responseText);
}
}
});
C# worked well
I just changed the JS because responseText was not working for me:
$.ajax({
type: "POST",
url: posturl,
contentType: false,
processData: false,
async: false,
data: requestjson,
success: function(result) {
if (result) {
$('body').html(result);
}
},
error: function (xhr, status, p3, p4){
var err = "Error " + " " + status + " " + p3 + " " + p4;
if (xhr.responseText && xhr.responseText[0] == "{")
err = JSON.parse(xhr.responseText).Message;
console.log(err);
}
});
You could use the Html.RenderAction helper in a View:
public ActionResult IsReady(int id)
{
if(true)
{
ViewBag.Action = "AnotherAction";
return PartialView("_AjaxRedirect");
}
return Json("pending");
}
And in the "_AjaxRedirect" partial view:
#{
string action = ViewBag.ActionName;
Html.RenderAction(action);
}
Reference:
https://stackoverflow.com/a/49137153/150342

Resources