How to bind the value in client side using ajax and mvc - asp.net-mvc

I need to bind the value in html list box. But ajax and return the value in client side. but it has the proper rerun value. I think Its return format is wrong. How to change this? My code is given below
public ActionResult value(bool sta1, bool sta2)
{
// my code
return Json(Selectedstudents.ToList(), JsonRequestBehavior.AllowGet);
}
ajax:
$.ajax({
//my code
dataType: 'json',
success: function (data) { // not trigger here
// my code
}
});

$.ajax ( {
url : "/ControllerName/Value"
type: 'Get'
data : { val1 : value1, val2:value2 }
datatype: 'json'
success : function(data) {
$("#listboxid").html(data);
do something...
}
});
and in controller
public JsonResult value(bool val1, bool val2)
{
// my code
result.Data = Selectedstudents.ToList();
result.JsonRequestBehavior = JsonRequestBehavior.AllowGet;
return result;
}

Related

Failed to call action method from AJAX

I have a JavaScript method dotrack(). I am calling an action UpdateJson from the JavaScript through AJAX. I am passing JSON data type and the method will return true/false. After executing system is going to success block but the returned value is not true/false.
My question is, whether the system is calling the action properly or not.
function doTrack() {
var D = { 'pageUrl': PageURL, 'linkUrl': linkURL, 'linkName': linkText, 'linkType': ControlType, 'leadId': LeadID, 'userType': UserType, 'portalId': PortalID, 'languageId': LanguageID, 'countryId': CountryID };
D = JSON.stringify(D);
$.ajax({
type: "POST",
url: "portal/UpdateJson",
data: D,
contentType: "application/json; charset=utf-8",
success: function (result) {
if(result == true)
alert("Success");
else
alert(result);
},
error: function (xhr, ajaxOptions, thrownError) {
alert(thrownError + " :: " + ajaxOptions);
//alert('unable to complete ajax request.');
}
});
}
Controller is Portal & Action is UpdateJson:
[HttpPost]
public ActionResult UpdateJson(string pageUrl, string linkUrl, string linkName, string linkType, string leadId, string userType, string portalId, string languageId, string countryId)
{
//do stuff
return Json(true);
}
Please help.
Your ajax code is working fine.
You just need to use the result variable directly instead of result.val.
success: function (result) {
exists = (result);
alert(exists);
}
If you want to use val property, you need to return an object that has val property too.
return Json(new { val = true });
Also you should use Url.Action for preventing incorrect URL.
url: "#Url.Action("UpdateJson", "portal")"

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.

Presenting Modal After Form Submission in MVC

I am trying to create a modal that will tell the user their submission was successfully submitted. This works fairly well, but the only problem is I have to declare each of my properties and assign it a value, then in the Json method I have accept all those parameters then do something with them. Is there any way to do this with a ViewModel? Or any otherway that this can be done using a ViewModel?
controller:
public Json Send(string var1, string var2)
{
...
if(valid)
return new Json(true, JsonRequestBehavior.AllowGet);
else
return new Json(false, JsonRequestBehavior.AllowGet);
}
javascript:
function submitData() {
$.ajax({
url: "/Report/Send",
type: "POST",
dataType: "json",
data: { var1 = Model.var1, var2 = Model.var2... },
success: function (data) {
if(data) {
showDialog();
}
else {
$("#errorDiv").load('Report/Error/');
}
},
error: function (somefunction) { }
});
}
Yes, create a ViewModel POCO class:
var myJsonResult = new { result: true };
return Json(myJsonResult);
You can also use a strongly typed ViewModel and return that:
var myJsonResult = new CustomResult { result: true };
return Json(myJsonResult);
Then just check that property on the class in your success function:
success: function (data) {
if(data.result) {
showDialog();
}
else if(!data.result) {
$("#errorDiv").load('Report/Error/');
}
},
EDIT:
You might also want to look at jquery's .serialize() method:
data: $("#myForm").serialize()
This will be useful if you bind your ViewModel to form elements and need to post them back to the server.

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.

jQuery Ajax call to controller

I'm new to Ajax and I'm trying to disable a checkbox if certain items are selected in a dropdown. I need to pass in the mlaId to the GetMlaDeliveryType(int Id) method in the RecipientsController.cs.
I'm not exactly sure how to set up the ajax call in the javascript function checkMlaDeliveryType(mlaId).
// MLA Add disable express checkbox if delivery type is electronic
$('.AddSelectedMla').change(function () {
var deliveryType = checkMlaDeliveryType($('.AddSelectedMla').val());
// disable express option if delivery type is Electronic
if (deliveryType == "Mail") {
$(".mlaExpressIndicator").removeAttr("disabled");
}else{
$(".mlaExpressIndicator").attr('checked', false).attr("disabled", true);
}
})
// ajax call to get delivery type - "Mail" or "Electronic"
function checkMlaDeliveryType(mlaId)
{
$.ajax({
type: "GET",
url: "/Recipients/GetMlaDeliveryType/" ,
data: mlaId,
dataType: ,
success:
});
}
RecipientsController.cs
public string GetMlaDeliveryType(int Id)
{
var recipientOrchestrator = new RecipientsOrchestrator();
// Returns string "Electronic" or "Mail"
return recipientOrchestrator.GetMlaDeliveryTypeById(Id);
}
EDIT:
Here's how the final javascript looked that worked
// MLA Add disable express checkbox if delivery type is electronic
$('.AddSelectedMla').change(function () {
checkMlaDeliveryType($('.AddSelectedMla').val());
})
// ajax call to get delivery type - "Mail" or "Electronic"
function checkMlaDeliveryType(mlaId)
{
$.ajax({
type: 'GET',
url: '#Url.Action("GetMlaDeliveryType", "Recipients")',
data: { id: mlaId },
cache: false,
success: function (result) {
// disable express option if delivery type is Electronic
if (result == "Mail") {
$(".mlaExpressIndicator").removeAttr("disabled");
} else {
$(".mlaExpressIndicator").attr('checked', false).attr("disabled", true);
}
}
});
}
$.ajax({
type: 'GET',
url: '/Recipients/GetMlaDeliveryType',
data: { id: mlaId },
cache: false,
success: function(result) {
}
});
then fix your controller action so that it returns an ActionResult, not a string. JSON would be appropriate in your case:
public string GetMlaDeliveryType(int Id)
{
var recipientOrchestrator = new RecipientsOrchestrator();
// Returns string "Electronic" or "Mail"
return Json(
recipientOrchestrator.GetMlaDeliveryTypeById(Id),
JsonRequestBehavior.AllowGet
);
}
Now your success callback will directly be passed a javascript instance of your model. You don't need to specify any dataType parameters:
success: function(result) {
// TODO: use the result here to do whatever you need to do
}
Set data in the Ajax call so that its key matches the parameter on the controller (that is, Id):
data: { Id: mlaId },
Note also that it's a better practice to use #Url.Action(actionName, controllerName) to get an Action URL:
url: '#Url.Action("GetMlaDeliveryType", "Recipients")'

Resources