Passing data from Controller to View using JSon object - asp.net-mvc

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();
});

Related

How to passing Controller a FormCollection and a class type object to action

i am facing problem to Passing Controller a Form Collection and a class type object to action using ajax call.
below are the my code.
[HttpPost]
public ActionResult AddDealNotes(DealNote objDealNote,FormCollection fc)
{
//code
}
To send a javascript ajax request using the jquery $.post object you need to make sure you use the dataType & contentType parameters.
<script>
function sendDealNotes(note, form)
{
var dataOutput = {"note": note,"form": form.serializeArray()};
var sendData = JSON.stringify(dataOutput );
var jqxhr = $.ajax({url:"/Controller/AddDealNotes", type:"POST", dataType:"json", contentType:"application/json",data:sendData})
.done(function() {
alert( "success" );
})
.fail(function(err) {
alert( "error" + err );
})
.always(function() {
alert( "complete" );
});
}
</script>

View not refreshing after AJAX post

I have a view (Index.cshtml) with a grid (Infragistics JQuery grid) with an imagelink. If a user clicks on this link the following jquery function will be called:
function ConfirmSettingEnddateRemarkToYesterday(remarkID) {
//Some code...
//Call to action.
$.post("Home/SetEnddateRemarkToYesterday", { remarkID: remarkID }, function (result) {
//alert('Succes: ' + remarkID);
//window.location.reload();
//$('#remarksgrid').html(result);
});
}
Commented out you can see an alert for myself and 2 attempts to refresh the view. The location.reload() works, but is basically too much work for the browser. The .html(result) posts the entire index.cshtml + Layout.cshtml double in the remarksgrid div. So that is not correct.
This is the action it calls (SetEnddateRemarkToYesterday):
public ActionResult SetEnddateRemarkToYesterday(int remarkID) {
//Some logic to persist the change to DB.
return RedirectToAction("Index");
}
This is the action it redirects to:
[HttpGet]
public ActionResult Index() {
//Some code to retrieve updated remarks.
//Remarks is pseudo for List<Of Remark>
return View(Remarks);
}
If I don't do window.location.reload after the succesfull AJAX post the view will never reload. I'm new to MVC, but i'm sure there's a better way to do this. I'm not understanding something fundamental here. Perhaps a nudge in the right direction? Thank you in advance.
As you requesting AJAX call, you should redirect using its response
Modify your controller to return JSONResult with landing url:
public ActionResult SetEnddateRemarkToYesterday(int remarkID) {
//Some logic to persist the change to DB.
var redirectUrl = new UrlHelper(Request.RequestContext).Action("Index", "Controller");
return Json(new { Url = redirectUrl });
}
JS Call:
$.post("Home/SetEnddateRemarkToYesterday", { remarkID: remarkID }, function (result) {
window.location.href = result.Url
});
After Ajax post you need to call to specific Url..
like this..
window.location.href = Url
When using jQuery.post the new page is returned via the .done method
jQuery
jQuery.post("Controller/Action", { d1: "test", d2: "test" })
.done(function (data) {
jQuery('#reload').html(data);
});
HTML
<body id="reload">
For me this works. First, I created id="reload" in my form and then using the solution provided by Colin and using Ajax sent data to controller and refreshed my form.
That looks my controller:
[Authorize(Roles = "User")]
[HttpGet]
public IActionResult Action()
{
var model = _service.Get()...;
return View(model);
}
[Authorize(Roles = "User")]
[HttpPost]
public IActionResult Action(object someData)
{
var model = _service.Get()...;
return View(model);
}
View:
<form id="reload" asp-action="Action" asp-controller="Controller" method="post">
.
.
.
</form>
Javascript function and inside this function I added this block:
$.ajax({
url: "/Controller/Action",
type: 'POST',
data: {
__RequestVerificationToken: token, // if you are using identity User
someData: someData
},
success: function (data) {
console.log("Success")
console.log(data);
var parser = new DOMParser();
var htmlDoc = parser.parseFromString(data, 'text/html'); // parse result (type string format HTML)
console.log(htmlDoc);
var form = htmlDoc.getElementById('reload'); // get my form to refresh
console.log(form);
jQuery('#reload').html(form); // refresh form
},
error: function (error) {
console.log("error is " + error);
}
});

How to use ajax json data by using jquery in mvc 4?

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.

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.

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');

Resources