Ajax redirect in ASP.NET MVC - c#

I am learning ASP.NET MVC and I am facing an issue in Ajax redirect. In normal post or get call we can return the user to some specific page like:
return RedirectToAction("AllStudents");
but using json, it's different or may be I don't know much about it.
I have posted my code in normal and also converted to Ajax.
What I have tried
Controller code in general:
[HttpGet]
public ActionResult Delete(int id)
{
stude.DeleteStudent(id);
return RedirectToAction("AllStudents");
}
and I have use Ajax which do the work successfully but it is not redirecting the user to another page, like in the above code it redirects the users to another page.
My Ajax controller code:
[HttpPost]
public JsonResult Delete(int id)
{
stude.DeleteStudent(id);
return Json("true",JsonRequestBehavior.AllowGet);
}
My Js code:
// Delete record
$("#del").click(function (e) {
e.preventDefault();
var id = $("#stid").val();
//alert(id);
$.ajax({
method: "POST",
url: "Delete/" + id,
contentType: "application/json; charset=utf-8",
async: true,
data: JSON.stringify(id),
success: function (data) {
console.log(data);
},
error: function (err) {
console.log('Failed to get data' + err);
}
});
});
The action is performed and data is deleted but the browser stop like:
updated
My goal: I want that the data is deleted without the page refresh, like it normally does. Also please share a link, post, something which shows the page refresh using ajax. like I want to refresh a page after every 1 minute but without reloading it.
Update: The data is now deleting but the Red highlighted (page) is not refreshing, I have to manually refresh, which I don't want. I want to refresh it silently without reload it.

if you will refresh the grid only then create a timeout method are follow as:
setTimeout(function() {get grid data by ajax call}, 10000);
if you want to reload the whole page then
create one partial view.
create an action method and return PartialView().
create ajax call and getting response to add in div like divid.html(data);
if you refresh the page every 1 min then create a time out function and create a simple ajax.
setTimeout(function() { ajax call}, 10000);

Related

ajax success returning undefined data object

I am returning a view from my action method which is called by ajax call.
but in ajax success it is returning undefined object. What is the Problem?
$.ajax({
type: "GET",
url: url,
success: function (data) {
if (typeof (data) === 'undefined') {
alert("Error");
return;
}else {
$('#content').html(data);
}
},
error: function () {
alert("Error");
return;
}
});
Backend code is here :-
public ActionResult Index()
{
return view(); //Index is a view containing only "hello world"
}
I think you declare a same variable in your code somewhere named data and assigned it undefined or you assigned "data = undefined" in console window.
If you do this either close the browser tab or browser itself.
And try again it should work.
For more detail refer following links :-
http://www.adequatelygood.com/JavaScript-Scoping-and-Hoisting.html
and
http://code.tutsplus.com/tutorials/javascript-hoisting-explained--net-15092
I am also using asp.net mvc and jquery ajax request in my application as well also tried your ajax code which is perfectly right. Possible reason for your error could be in your return view() like it could not be find.
One most another thing is as you are using ajax request it will not show any error directly for that you have to inspect in your browser console. I hope you will find problem while you inspect in your browser.

Sending $ajax via jQuery to C# codebehind not working

I am having unexplained behavior when I post from jquery using ajax to C#.
1) The main page is called not the method I am requesting in jQuery.
To work around this I simply put an if in the page load so that if a particular item is in the querystring it will trigger a series of commands. It does hit that if statement and runs the code perfectly fine. There are some methods that do things like change a color on the map. These never actually happen. I can set a label and it will pass right over it but the label remains unset.
2) strangely enough.... my page has a timer with a refresh on it. It refreshes the page and now the changes are processed.
Here is the way I am calling my method in jQUery:
function mycmethod(param)
{
//alert(precinct);
$.ajax({
url: "myPage.aspx/someMethod",
type: 'POST',
data: "params=" + param,
success: function iGotData(responseJSON) {
// alert("Worked");
},
error: function (xhr, status, errorThrown) {
console.log("Error: " + errorThrown);
console.log("Status: " + status);
console.log(xhr);
alert("Didnt work:" + errorThrown);
},
})
};
It was originally set to async: true but that didn't make a difference.
The method its not calling on load is:
[WebMethod][ScriptMethod]
public Boolean someMethod(string param)
{
setFeatures();
GenerateMap();
return true;
}
I doubt its relevant but I am calling a jquery call with over mouse over of a specific element. That jquery calls a function which calls a asmx web service that returns some jSON. I am calling the mycmethod after the JSON is returned.
Why is my UI elements not responding until the page refreshes. If not, is there a way I can force a refresh like the timer does?
[WebMethods] methods should be declared as static.
I've also found that you might need to specify the content type in your ajax call:
contentType: "application/json; charset=utf-8"
Also, your data option looks suspicious. Maybe you should append it to the url option:
url: "myPage.aspx/someMethod?params" + parm
or, more ideally, send it as either a JSON object or a JSON string:
data: {
params: param
}
or
data: JSON.stringify({
params: param
})
If I understand you correctly, you're loading the page, then calling the server via ajax and expecting the server to change UI elements of the currently loaded page.
It doesn't work like that, unfortunately. Once you've served the page, the server itself cannot manipulate that page without doing a refresh/post back (or something along those lines).
If you want to update the UI without doing a refresh/post back you can have your WebMethod return HTML, and your jQuery success method can update the relevant controls.
Alternatively you could use jQuery's .get() to retrieve a fresh copy of the page via ajax, and update your current page like that. (although it's less efficient)

Update the Page without refresh it

Goal:
When you click on the row (1), new data shall display (3.) without the whole webpage will be updated/refreshed.
Problem:
1.
I need advice and I don't know where to find the funciton to display the picture number 2 and how to display the data and new object (3.) without update/refresh the whole webpage?
And
2
How do you create an icon to display loading picture?
Information:
- The page is based on ASP.mvc with C#
Use ajax functionality of either jquery or MVC ajax helpers.
You can find jquery ajax here.
and MVC ajax helper lib here
and here
you can make an ajax call to the server's websevice and it can return one of the well known web format (for e.g. json or XML). When the webservice call returns you can then "inject" the data in your html page with either javascript (dom manipulation) or using MVC helpers.
Here's one that could help..
http://www.asp.net/mvc/tutorials/older-versions/javascript/creating-a-mvc-3-application-with-razor-and-unobtrusive-javascript
You Can use jquery ajax which would call async action method(function). Data is returned the form of Json. You can write code to deserilize data and display it using jquery.
Create a Action method which would return JsonResult as viewresult as
public JsonResult GetJsonData()
{
return Json(new
{ testDataResult =TestDataResultObj.Data
JsonRequestBehavior
}, JsonRequestBehavior.AllowGet);
}
and write following jquery code:-
if (GetDataAsyc()) {
$.ajax({
type: "GET",
data: { testData: testDataResult },
url: url,// url of action method to be called asynch
dataType: "json",
cache: false,
traditional: true,
contentType: "application/json",
success: function (data) {
// on success assign testDataResult to messages //line
$("#MessagesLines").html(testDataResult .Html);
}
},
error: function () {
//Display error message
$("ErrorMsg").html("There was error whey trying to process your request")
}
});
}
Use ajax+PartialViews to update some page sections

Redirect a page inside a async method

Requirement:
User calls a page and I display page is loading while i execute a method in background and redirect to the url that the method returns.
Tried using async method call in pageload ,pagenotredirected as already loaded.
Tried updating textbox from the async method and call textboxonchange not working as page aleady loaded
Have added the code for ajax per ur suggestion please review
I call a async method inside pageload and in the pageload I display loading message ,after the async methos completes I get a url ,iam trying to redirect to that url but iam unable to do it inside the async as the page is already loaded ,so iam updating an hidden textbox with this url and using the onchange event in that text box and redirecting but still the page is not redirected,can someone please suggest a better way to do this-Thanks
<asp:TextBox runat="server" ID="urlTextBox" Value="" Style="display:none;" AutoPostBack="true" ></asp:TextBox>
$(document).ready(function () {
$('#urlTextBox').change(function () {
var keyword = $("#urlTextBox").val();
if (keyword.length > 0) {
window.location.href = keyword;
}
});
urlTextBox.Text = url;
the urltextbox gets value inside the async method as I process a long running process inside the async to get this url
I have added a js file in which I call the c# method like this
$(document).ready(function () {
$('#outputFromCmdLine').Text = "Loading...";
GetOutputFromCommandLine();
});
function GetOutputFromCommandLine() {
$.ajax({
type: "POST",
url: "Page.aspx/ConvertToBatch", //url to point your webmethod
contentType: "application/json; charset=utf-8",
dataType: "json",
async:true,
success: function (Result) {
window.location.href = Result;
},
error: function (request, status, error) {
alert(request.responseText);
}
});
and the c# method is sync method and returns the url like this
[System.Web.Services.WebMethod()]
public static string ConvertToBatch()
{
some process
return urlstring;
}
I also added the js file name in top of aspx page ,but nothing gets called ,is this the right way to do it
<script type="text/javascript" src="/Scripts/jqueryFile.js"></script>
Instead of calling the async method from inside the page load you should call it using AJAX in JavaScript once the page is loaded. Then you can use the response from the AJAX request to retrieve the URL with which to trigger navigation to.
<script>
$(function()
{
$.ajax(
{
url: "/api/request",
}).done(function(responseUrl)
{
window.location.href = responseUrl;
});
});
</script>
This will wait for the page to be loaded, make some request to the server, and navigate to the response string (expecting the HTTP response body to be a URL).
I think you would use an ASMX web service or better yet an ASP.NET Web API controller to handle the actual request/response.
I know that with Visual Studio 2013 you can create an ASP.NET Web Forms project which includes Web API and configures them automatically to work together. If you are working with an existing project you could add Web API as a NuGet package and add the appropriate plumbing to make it work manually by simply looking at the VS2013 wizard-generated project as an example of how it is done.
EDIT:
It seems you found another way to handle AJAX calls which is using a WebMethod. WebMethods are described in this question.

jQuery does not load response

I normally use ASP.NET MVC 2, but there were some problems with it, so I began to work with ASP.NET MVC 2 + jQuery and everything works. But there is one problem, jQuery doesn't load my reponse. On the ASP.NET MVC side I'm redering a partial view and I also get the respone on the client, but nothing is rendered. How can I solve this?
Here is the jquery code:
function addCredential(state, id) {
var daten = getJson(state, id);
$.ajax(
{
type: "POST",
url: "/Account/SetCredential/",
data: daten,
dataType: "json",
success: function(partialView) {
$('#Credentials').replaceWith(partialView);
location.reload();
}
});
return true;
};
function getJson(state,id) {
var username = $('#username').val();
return {"username": username, "credential_id": id , "state": state };
};
The problem looks like location.reload();
That's reloading your page after you update it with AJAX, effectively returning it's state back to the way it was before you inserted the content with .replaceWith()
UPDATE: looks like you're using dataType: "json" and inserting that into the DOM? That's probably also a problem. If the view is being returned as HTML, you should replace that with dataType: "html"
#Konrad, try using the JSON2 library (http://www.json.org/js.html) to alert the "partialView" object in your success function to see what you're getting prior to reloading the page. Also, make sure $('#Credentials') is returning an object. When I run into issues when trying to select elements on the page, I usually check the length value of the jQuery object that is returned. If length = 0, then you're not getting the element.
UPDATE:
Also, if you're trying to inject HTML into $('#Credentials'), then partialView may not be the correct format. The success function accepts an object argument which comes from parsing of the responseText of the web method you called to get what you call partialView.
UPDATE:
Check http://encosia.com/2010/03/03/asmx-and-json-common-mistakes-and-misconceptions/ for more info using $.ajax. Lots of great info on this blog.
UPDATE:
This is how I use JSON lib to view the data that is returned.
alert(JSON.stringify(partialView));

Categories