Multiple AJAX requests in MVC3 application - ajax

The situation, I'm making multiple ajax/json requests on the same page to a controller, which returns a JsonResult.
I know this is a problem with the session state, I've added the [SessionState(SessionStateBehavior.Disabled)] attribute on my controller class, but nothing seems to work, my second ajax request just wont get the return data.
the controller:
[SessionState(SessionStateBehavior.Disabled)]
public class IndexController : Controller
{}
the two json methods:
[AcceptVerbs(HttpVerbs.Get)]
public JsonResult GetLatestListJSON()
{
Thread.Sleep(5000);
ArticleRepository repo = new ArticleRepository();
IList<ArticleModel> list = repo.GetLatestContent(10);
return Json(list, JsonRequestBehavior.AllowGet);
}
[AcceptVerbs(HttpVerbs.Get)]
public JsonResult GetCustomerJSON()
{
Thread.Sleep(5000);
CustomerRepository Repo = new CustomerRepository();
IList<Customer> cust= Repo.GetCustomer();
return Json(cust, JsonRequestBehavior.AllowGet);
}
The second ajax call, the other one is very similar, I never get to see the 'succes'-alert.
<script type="text/javascript">
$(document).ready(function () {
alert('before');
$.getJSON("/Index/GetCustomerJSON", null, function (data) {
alert('succes');
$("#loadingGifVideo").hide();
$.each(data, function (index, mod) {
});
});
});
Thanks guys :)

If you put a break-point in your GetCustomerJSON method and run this in Visual Studio does the method ever get called? It does
EDIT
Try switching from getJSON to the ajax method so you can capture any errors. Like so:
$.ajax({
url: "/Index/GetCustomerJSON",
dataType: 'json',
data: null,
success: function (data) { alert('success'); }
error: function (data) { alert('error'); }
});
Do you get an "error" alert?

Related

Ajax and ASP.NET MVC- Get page URL, not the controller/action URL

I have an Ajax method that calls an MVC action from a controller class.
$.ajax({
type: "GET",
contentType: "application/json; charset=utf-8",
url: "/ajax/Updates/Message",
dataType: "json",
success: function (response) {
//data variable has been declared already
data = response;
},
complete: function () {
if (data !== "") {
$('#div1').text(window.location.path);
$('#div2').text(data);
}
},
});
[HttpGet]
public async Task < ActionResult > Message()
{
string d = "test string";
return Json(d, JsonRequestBehavior.AllowGet);
}
The 'url' within the Ajax method is the call to the action method.
What to do if I want to return the actual page URL in Ajax Response, not the controller/action url?
So this controller does not have a view or anything associated with it, it is more like a helper class. When I am using ajax in any of the other pages, it is not returning the URL path of that specific page (via 'window.location.path) e.g. /Accounts/Summary , rather it is returning Updates/Message (in reference to the controller and action)
The web is stateless, when you call Updates/Message with ajax, it doesn't know it's for page Accounts/Summary. You'll have to pass this as parameter (post or get) or you could try Request.UrlReferrer which should contain the url of the page that called the request.
I hope this will help you try this code:
ajax code
$.ajax({
type: 'GET',
url: '#Url.action("Message","Updates")', // url.action(ActionName,ControllerName)
success: function (data) {
window.location = data;
},
error: function (xhr) { // if error occured
alert("Error occured.please try again");
}
dataType: 'json'
});
actionresult :
[HttpGet]
public async Task<ActionResult> Message()
{
string d = "http://www.google.com";
return Json(d, JsonRequestBehavior.AllowGet);
}

Ajax not returning desired results or not working at all

I have been trying to load return a JsonResults action from a controller in MVC using ajax call. I can see that the alert() function is triggering well but the ajax is not executing. I have search for several sources but to no avail.
public JsonResult FillBusinessLicenceL3(int? selectedID)
{
var bl3_Items = db.LevelThreeItems.Where(l3 => l3.LevelTwoItem_ID == selectedID);
return Json(bl3_Items, JsonRequestBehavior.AllowGet);
}
The below too is the javascript calling for the json method.
<script>
function FillBussLicence_L3items() {
alert("You have clicked me");
var bl2_Id = $('#BussLicenceL2_ID').val();
//alert(document.getElementById("BussLicenceL2_ID").value);
alert(bl2_Id);
$.ajax({
url: 'StartSurvey/FillBusinessLicenceL3/' + bl2_Id,
type: "GET",
dataType: "JSON",
data: "{}", // { selectedID : bl2_Id },
//contentType: 'application/json; charset=utf-8',
success: function (bussLicence_L3items) {
$("#BussLicenceL3_ID").html(""); // clear before appending new list
$.each(bussLicence_L3items, function (i, licenceL3) {
$("#BussLicenceL3_ID").append(
$('<option></option>').val(licenceL3.LevelThreeItem_ID).html(licenceL3.LevelThreeItem_Name));
});
}
});
}
Also, I have tried this one too but no execution notice.
Thanks a lot for your help in advance.
After looking through the browser's console, I noticed that the LINQ query was tracking the database and was creating a circular reference so I changed the query to the following and voila!!
public JsonResult FillBusinessLicenceL3(int? selectedID)
{
var bl3_Items = db.LevelThreeItems.
Where(k => k.LevelTwoItem_ID == selectedID).
Select(s => new { LevelThreeItem_ID = s.LevelThreeItem_ID, LevelThreeItem_Name = s.LevelThreeItem_Name });
return Json(bl3_Items, JsonRequestBehavior.AllowGet);
}
There was nothing wrong with the ajax call to the controller.

How to use ajax in asp.net MVC

How can I return a class object from Ajax in asp.net MVC....???
Example:
Ajax call from html:
$.ajax({
type: 'POST',
url: '/Tutorial/Web/AlignmentRule/GetAlignmentDetails',
data: { alignmentRuleId: alignmentRuleId },
success:
function (data) {
alert(data.Id);
alert(data.alignmentData.Id);
$("#ruleName").val(data.alignmentData.Name);
$("#level").val(data.alignmentData.Id);
},
error:
function () {
alert("Server Error!!!!");
},
dataType: 'JSON',
async: false
});
and Action method in contorller is:
public virtual JsonResult GetAlignmentDetails(int alignmentRuleId)
{
var alignmentData = _allignmentRuleRepository.GetAlignmentById(alignmentRuleId);
return Json( alignmentData );
}
And I want to return a list of alignmentRule class objects also....
you can compose your return object as you want, for example, create a ViewModel as decorator to hold everything you want to pass, like:
var json = new JsonViewModel() {
alignmentData = alignmentData,
rules = yourRules
};
return Json(json);
The error is thrown because by default MVC framework does't allow you to respond to an HTTP GET request with a JSON (because of security reasons).
In order to make it work, when you retrurn Json in your action, you need to specify JsonRequestBehavior.AllowGet
[HttpPost]
public virtual JsonResult GetAlignmentDetails(int alignmentRuleId)
{
var alignmentData = _allignmentRuleRepository.GetAlignmentById(alignmentRuleId);
return Json( alignmentData, JsonRequestBehavior.AllowGet);
}
EDIT
Annotate your action with [HttpPost] attribute.
For further investigation on this topic check this article

How I can pass FormCollection object with $.ajax(...)

I am working C# MVC application and I have 2 action method in a controller:
[MultipleButton(Name = "action", Argument = "Save")]
public ActionResult SaveBasicInformation(FormCollection collection)
{.....}
[MultipleButton(Name = "action", Argument = "Submit")]
public ActionResult SubmitRequest(FormCollection collection)
{....}
The above code is working fine without ajax request. Now my question is how i can to pass "FormCollection" in $.ajax(..) for specific controller method.
var input = $(':input');
$.ajax({
url: '#Url.Action("SaveBasicInformation", "Home")',
type: 'POST',
cache: false,
data: input,
success: function (data) {
alert("Success");
},
error: function (result) {
alert("Error");
alert(result.responseText);
}
});
Here is the error message when i use the above ajax code:
The current request for action 'SaveBasicInformatio'' on controller type HomeController'
is ambiguous between the following action methods: System.Web.MVC.Action Result
SubmitRrquest(System.Web.formCollection)....
Thank you for your help...
The `[MultipleButton]' attribute is a custom attribute possibly from this SO answer? which may be causing the problem as its an ajax call. Try removing the attributes.

Zend Framework: How to call a Function (not a Controller Action) using ajax?

Assume that I have a public function in IndexController called test():
public function test(){
//some code here
}
In index.phtml view file, I want to use JQUERY AJAX to call test() function but have no idea about this.
Code:
Click me to call test() function()
<script>
callTestFunction = function(){
$.ajax({
type: "POST",
Url: ***//WHAT SHOULD BE HERE***
Success: function(result){
alert('Success');
}
});
}
</script>
I would suggest writing an action for it. If there is logic inside of test() that you need other actions to be able to use, the factor that out.
There are a couple of reasons for having it be its own action:
You can test the results of the action directly instead of having to go through a proxy.
You can take advantage of context switching depending on if you need JSON returned or HTML
It is an action that you are trying to hit via AJAX, so there's no need to hide it.
Remember that not every action has to be its own full fledged page. One thing to make sure you do is disabling the auto-rendering of the view inside this action so it doesn't complain about not being able to find it.
public function ajaxproxyAction(){
if (is_callable($_REQUEST['function_name'])) {
return call_user_func_array($_REQUEST['function_name'], $_REQUEST['function_params'])
}
}
<script>
callTestFunction = function(){
$.ajax({
type: "POST",
Url: '/controller/ajaxproxy/',
data: { function_name: 'echo', function_params: 'test' }
Success: function(result){
alert('Success');
}
});
}
</script>
public function ajaxproxy2Action(){
if (method_exists($this, $_REQUEST['function_name'])) {
$retval = call_user_func_array(array($this, $_REQUEST['function_name']), $_REQUEST['function_params']);
echo json_encode(array('function_name' => $_REQUEST['function_name'], 'retval' => $retval));
die;
}
}
just think about this way ;)

Resources