How to use ajax json data by using jquery in mvc 4? - asp.net-mvc

How to use $.post or $.getJSON to get json from mvc controlller but not working below? Would you like help me?
var controlRole = function () {
var _url = 'IsStudent/';
console.log('IsStudent');
$.post(_url, {}, function (data) {
console.log('IsStudent2');
if (data == "true") {
$('#btnSent_').hide();
$('#btnDraft_').hide();
$('#btn_Inbox_').show();
$('#btnTrash_').show();
$.post('FillProgramListByUser/', {}, function (result) {
console.log('IsStudent3');
console.log(result);
$("#liProgramContainer ul").append('<li ><a class="btn" href="javascript:;" data-title="Sent">'+result.Name+'</a><b></b></li>');
});
// $.getJSON("FillProgramListByUser/", user, updateFields);
}
else {
$('#btnSent_').show();
$('#btnDraft_').show();
$('#btn_Inbox_').show();
$('#btnTrash_').show();
}
});
}
Controller side:
public JsonResult FillProgramListByUser()
{
string UserName = SessionVariables.CurrentUser.UserName;
int OrganizationId = SessionVariables.CurrentUser.OrganizationId;
IList<Program> programs = new List<Program>();
if (UserName != "system_admin")
{
programs = Uow.Programs.GetAll().Where(q => q.OrganizationId == OrganizationId).ToList();
}
return Json(programs, "application/json", Encoding.UTF8, JsonRequestBehavior.AllowGet);
}
[HttpPost]
public string IsStudent()
{
string UserName = SessionVariables.CurrentUser.UserName;
if (UserName != "system_admin")
{
return "true";
}
else
{
return "false";
}
}

Your controller action should return a JsonResult and not some strings:
[HttpPost]
public ActionResult IsStudent()
{
string UserName = SessionVariables.CurrentUser.UserName;
if (UserName != "system_admin")
{
return Json(new { success = true });
}
return Json(new { success = false });
}
Also in your FillProgramListByUser action you don't need to be explicitly setting the content type response header nor the encoding:
public ActionResult FillProgramListByUser()
{
string UserName = SessionVariables.CurrentUser.UserName;
int OrganizationId = SessionVariables.CurrentUser.OrganizationId;
IList<Program> programs = new List<Program>();
if (UserName != "system_admin")
{
programs = Uow.Programs.GetAll().Where(q => q.OrganizationId == OrganizationId).ToList();
}
return Json(programs, JsonRequestBehavior.AllowGet);
}
Also adapt your script so that the urls are not hardcoded as in your example but you used URL helpers to generate them:
<script type="text/javascript">
var controlRole = function () {
var isStudentUrl = '#Url.Action("IsStudent")';
$.post(isStudentUrl, function (data) {
if (data.success) {
$('#btnSent_').hide();
$('#btnDraft_').hide();
$('#btn_Inbox_').show();
$('#btnTrash_').show();
var fillProgramListByUserUrl = '#Url.Action("FillProgramListByUser")';
$.post(fillProgramListByUserUrl, function (result) {
$("#liProgramContainer ul").append('<li><a class="btn" href="javascript:;" data-title="Sent">'+result.Name+'</a><b></b></li>');
});
} else {
$('#btnSent_').show();
$('#btnDraft_').show();
$('#btn_Inbox_').show();
$('#btnTrash_').show();
}
});
};
</script>
Next put breakpoints in your controller actions and see if they are hit. Also don't forget to look at the network tab of your javascript debugging tool (FireBug or Chrome Developer Toolbar) which is where you will see the exact AJAX request being sent to the server and what does the server respond to. You will see the HTTP status code returned and you could also see the contents of the response. If the status code is non 2xx the success callback of your AJAX request will not be executed.
Another thing you should check is the Program model which is being returned by your FillProgramListByUser controller action. In there you are attempting to JSON serialize an IList<Program> but be careful: if this Program class has some circular references (often happens if you don't use view models but are directly passing your EF domain models to the views) you won't be able to JSON serialize it. The answer is of course obvious: use a view model.

Related

How can I do multiple post parameters in web api?

I have a web-api, 2 tables in my SQL DB, JT and Sales. Before I add() to the database I need the poster to specify first in the uri whether he/she wants to post to JT table or Sales. My problem is that my post method only accepts one model binding, it doesn't want two like as shown on my code below. It doesn't have errors but when I post with that logic in mind it returns an error in POSTMAN that It can't bind multiple parameters ('JT' and 'Sales') to the request's content.
Here is my code:
[ResponseType(typeof(JT))]
public HttpResponseMessage PostJT(JT JT, Sales Sales, [FromUri] string tran)
{
try
{
if (ModelState.IsValid)
{
if (tran == null)
{
return Request.CreateResponse(HttpStatusCode.Unauthorized, "Unauthorized Access!");
}
else
{
switch (tran)
{
case "JT": db.JTs.Add(JT);
break;
case "sales": db.Sales_.Add(Sales);
break;
}
}
db.SaveChanges();
return Request.CreateErrorResponse(HttpStatusCode.OK, "Added!");
}
//below are just elses with return messages.
There is no direct way to pass multiple parameter but you can use the below work around
This link gives complete details on Web API passing Multiple parameter
$.ajax(
{
url: "samples/PostAlbum",
type: "POST",
contentType: "application/json",
data: JSON.stringify({ JT: jt, Sales: sales, UserToken: userToken }),
success: function (result) {
alert(result);
}
});
[HttpPost]
public string PostAlbum(JObject jsonData)
{
try
{
if (ModelState.IsValid)
{
if (tran == null)
{
return Request.CreateResponse(HttpStatusCode.Unauthorized,
"Unauthorized Access!");
}
else
{
dynamic json = jsonData;
JObject jtObject = json.JT;
JObject salesObject = json.Sales;
var jt = jtObject.ToObject<JT>();
var sales = salesObject.ToObject<Sales>();
if (jt != null)
{
db.JTs.Add(JT);
}
else if (sales != null)
{
db.Sales_.Add(Sales);
}
}
db.SaveChanges();
return Request.CreateErrorResponse(HttpStatusCode.OK, "Added!");
}
//below are just elses with return messages.
}

Get Boolean Value and use it in Ajax call to controller

I have this javascript code to call a function from my controller that returns a boolean value
<script type="text/javascript">
$(function () {
$(document).ready(function NumberAmt() {
$.ajax({
url: 'CallCenter/CallCenterAmt',
type: 'Get',
contentType: 'application/json;',
success: function (data) {
}
});
})
});
I want to be able to use that boolean value in a function in the javascript on my page load to figure out what to display from my view. Please help Thanks
THis is the Controller Function it is calling
[HttpPost]
public ActionResult CallCenterAmt()
{
bool threeNumbers=false;
try
{
using (var entities = new OpenRoad.Data.Repository.OpenRoadEntities())
{
var CallCenterNumberAmt = (from c in entities.CallCenterNumberAmts
where c.SiteId == OpenRoad.Web.Session.SiteId
select c).FirstOrDefault();
if (CallCenterNumberAmt == null)
{
CallCenterNumberAmt = new Data.Repository.CallCenterNumberAmt();
CallCenterNumberAmt.SiteId = OpenRoad.Web.Session.SiteId;
CallCenterNumberAmt.ThreeNumbers = false;
entities.CallCenterNumberAmts.Add(CallCenterNumberAmt);
entities.SaveChanges();
}
else
{
if (CallCenterNumberAmt.ThreeNumbers == true)
{
threeNumbers= true;
}
else
threeNumbers= false;
}
}
}
catch
{
}
return Json(threeNumbers);
}
}
Your data should contain the value. You need to make sure you're actually returning JSON, then call it based on the variable
e.g. {YourVariable: true}
success: function(data) {
if(data.YourVariable) {
//true
}
}
Instead of the Controller method returning a boolean, have it return a JSON object containing a boolean instead.
i.e. { isOkay : true }
Then in your Ajax call, you can check to make sure that the controller returned what you thought it did by using data.hasOwnProperty("isOkay") and then using the value of isOkay to determine whatever else you need to.

Passing data from Controller to View using JSon object

I have the following to get the Json abject passed from the controller and populate the various textboxes in the view. However, nothing is happening even though controller is passing a valid Json object. What is wrong with this code???
<script language="javascript" type="text/javascript">
$(document).ready(function() {
var url = '<%=Url.Action("DropDownChange") %>';
$("#vendorID").change(function() {
var selectedID = $(this).val();
if (selectedID != "New Vendor Id") {
//$.post('Url.Action("DropDownChange","Refunds")', function(result) {
$.post(url, { dropdownValue: selectedID }, function(result) {
alert(selectedID);
$("#name").val(result.Name);
$("#city").val(result.City);
$("#contact").val(result.Contact);
$("#address2").val(result.Address2);
$("#address1").val(result.Address1);
$("#state").val(result.State);
$("#zip").val(result.Zip);
});
}
});
});
This is the code in my controller;
public JsonResult DropDownChange(string dropdownValue)
// This action method gets called via an ajax request
{
if (dropdownValue != null && Request.IsAjaxRequest() == true)
{
paymentApplicationRefund =
cPaymentRepository.PayableEntity(dropdownValue);
paymentApplicationRefund.Address1.Trim();
paymentApplicationRefund.Address2.Trim();
paymentApplicationRefund.Name.Trim();
paymentApplicationRefund.City.Trim();
paymentApplicationRefund.Contact.Trim();
paymentApplicationRefund.State.Trim();
paymentApplicationRefund.Zip.Trim();
return Json(paymentApplicationRefund,"application/json");
}
else
{
return null;
}
}
You probably just need to tell it to expect JSON data back. By default it assumes it's HTML.
$.post(url, { dropdownValue: selectedID }, function(result) {
alert(selectedID);
$("#name").val(result.Name);
$("#city").val(result.City);
$("#contact").val(result.Contact);
$("#address2").val(result.Address2);
$("#address1").val(result.Address1);
$("#state").val(result.State);
$("#zip").val(result.Zip);
}, 'json');
I prefer sending Json to a ActionResult with my DTO as the parameter and use the JsonValueProviderFactory do the deserialization for me.
Sending JSON to an ASP.NET MVC Action Method Argument
Try this...
Add the ".change()" at the end of the function.
$(document).ready(function() {
var url = '<%=Url.Action("DropDownChange") %>';
$("#vendorID").change(function() {
.....
}).change();
});

JSON RedirecttoAction

I am trying to change a value in a table from one view, and then redirect to another view using Flash FSCommand and Json, using the following code:
if (command == "nameClip") {
var url = '<%= Url.Action("Index", "Home") %>';
var clip = [args];
try {
$.post(url, {
MovieName: clip
}, function(data) {
;
}, 'json');
} finally {
// window.location.href = "/Demo/SWF";
}
}
In the controller:
[AcceptVerbs(HttpVerbs.Post)]
public ActionResult Index(SWF movietoplay) {
var oldmovie = (from c in db.SWFs where c.ID == "1" select c).FirstOrDefault();
var data = Request.Form["MovieName"].ToString();
oldmovie.SWFName = data;
db.SubmitChanges();
return RedirectToAction("Show");
}
All works well except Redirect!!
You need to perform the redirect inside the AJAX success callback:
$.post(url, { MovieName: clip }, function(data) {
window.location.href = '/home/show';
}, 'json');
The redirect cannot be performed server side as you are calling this action with AJAX.
Also you indicate in your AJAX call that you are expecting JSON from the server side but you are sending a redirect which is not consistent. You could modify the controller action to simply return the url that the client needs to redirect to using JSON:
[AcceptVerbs(HttpVerbs.Post)]
public ActionResult Index(SWF movietoplay)
{
...
return Json(new { redirectTo = Url.Action("show") });
}
and then:
$.post(url, { MovieName: clip }, function(data) {
window.location.href = data.redirectTo;
}, 'json');

How to redirect to a controller action from a JSONResult method in ASP.NET MVC?

I am fetching records for a user based on his UserId as a JsonResult...
public JsonResult GetClients(int currentPage, int pageSize)
{
if (Session["UserId"] != "")
{
var clients = clirep.FindAllClients().AsQueryable();
var count = clients.Count();
var results = new PagedList<ClientBO>(clients, currentPage - 1, pageSize);
var genericResult = new { Count = count, Results = results };
return Json(genericResult);
}
else
{
//return RedirectToAction("Index","Home");
}
}
How to redirect to a controller action from a JsonResult method in asp.net mvc?Any suggestion...
EDIT:
This doesn't seem to work...
if (Session["UserId"] != "")
{
var clients = clirep.FindAllClients().AsQueryable();
var count = clients.Count();
var results = new PagedList<ClientBO>(clients, currentPage - 1, pageSize);
var genericResult = new { Count = count, Results = results ,isRedirect=false};
return Json(genericResult);
}
else
{
return Json({redirectUrl = Url.Action("Index", "Home"), isRedirect = true });
}
This will depend on how you are invoking this controller action. As you are using JSON I suppose that you are calling it in AJAX. If this is the case you cannot redirect from the controller action. You will need to do this in the success callback of the AJAX script. One way to achieve it is the following:
return Json(new
{
redirectUrl = Url.Action("Index", "Home"),
isRedirect = true
});
And in the success callback:
success: function(json) {
if (json.isRedirect) {
window.location.href = json.redirectUrl;
}
}
Remark: Make sure to include isRedirect = false in the JSON in case you don't want to redirect which is the first case in your controller action.
Adding to Darin Dimitrov's answer. For C#.NET MVC - If you want to redirect to a different page/controller and want to send an Object/Model to the new controller, You can do something like this.
In the JsonResult Method (in the controller):
ErrorModel e = new ErrorModel();
e.ErrorTitle = "Error";
e.ErrorHeading = "Oops ! Something went wrong.";
e.ErrorMessage = "Unable to open Something";
return Json(new
{
redirectUrl = Url.Action("Index", "Home",e),
isRedirect = true
});
And in the success callback:
success: function(json) {
if (json.isRedirect) {
window.location.href = json.redirectUrl;
}
}
And if the new controller can accept the model/object like below.. you can pass the object to the new controller/page
public ActionResult Index(ErrorModel e)
{
return View(e);
}
Hope this helps.
What to do you think about trying to call:
return (new YourOtherController()).JSONResultAction();
instead of using redirects?
And if you work with areas ...
Controller:
return Json(new
{
redirectUrl = Url.Action("Index", "/DisparadorProgSaude/", new { area = "AreaComum" }),
isRedirect = true
});
View:
success: function (json) {
if (json.isRedirect) {
window.location.href = json.redirectUrl;
}
},
No way to do this, the client is executing an AJAX script so will not be able to handle anything else.
I suggest you redirect in the client script based on the returned data in the callback function.
Take a look at a similar question here: http://bytes.com/topic/javascript/answers/533023-ajax-redirect

Resources