Update the Page without refresh it - c#

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

Related

Ajax redirect in ASP.NET MVC

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

Call method in code-behind (secure page) from client (JavaScript)

Let me start of by saying I am very new to ASP.NET and C#.
I have a simple web form containing data which I want to send to a code-behind page.
The idea is to capture the data and send it as a JSON object to a code-behind method.
Note that this is done via JavaScript/AJAX (see code below).
The code-behind method will then do a trivial HTTP "PUT" request to update the data.
The .apsx page is located in the Secure folder (uses a Secure Master).
Don't know if that will affect the method calling?
Following is the code I have thus far.
JavaScript/AJAX:
var saveOptions =
{
url: "Profile.aspx/UpdateVendor",
type: "PUT",
dataType: 'json',
data: JSON.stringify({ vendor: ko.mapping.toJS(vendor) }),
contentType: "application/json",
success: function (response)
{
}
}
Code-behind:
namespace PartyAtVendors.Secure
{
[WebService]
public partial class Profile : System.Web.UI.Page
{
[WebMethod]
public static bool UpdateVendor(PartyAtApi.Models.Vendors vendor)
{
return true;
}
}
}
Update:
Problem is as follows. The codebehind method isn't called. When I run and test the code and use Chrome's "inspect element" I receive the error:
PUT http://localhost:50671/Secure/Profile.aspx/UpdateVendor 404 (Not Found)
Such static methods are called Page Methods in asp.net.
You call them form javascript like this on the same page as follows:
string data = "{mydata:myvalue}";
PageMethods.UpdateVendor(data);
You need to have a ScriptManager on the page and it should have PageMethods enabled
<asp:ScriptManager runat="server" EnablePageMethods="true">
</asp:ScriptManager>
The page method must be defined on the page. It cannot be defined in a control, master page, or base page.
PageMethods only support HTTP POST(Even when you call them without the javascript proxy of PageMethods). You can read the details of this security limitation in this blog post by Scott Guthrie. Using the PUT verb is causing the 404 error.
ASP.NET AJAX 1.0 by default only allows the HTTP POST verb to be used
when invoking web methods using JSON
Your webmethod & javascript method should be on same page.
Hi managed to sort out what was wrong.
I simply changed the HTTP method to "POST" as follows:
var saveOptions =
{
url: "Profile.aspx/UpdateVendor",
type: "POST",
dataType: 'json',
data: JSON.stringify({ vendor: ko.mapping.toJS(vendor) }),
contentType: "application/json",
success: function (response)
{
}
}
$.ajax(saveOptions);
This seemed to fix the problem and now I am able to send the JSON data to the codebehind method using AJAX.

Saving changes to a jQuery sortable table

I have a table where the users are allowed to drag and drop rows in the order they want, and then save them. I have no problem with getting the drag and drop part to work. It's the saving I'm having issues with. I'm sending an Ajax call to a web service which will then make the save. I can't seem to actually catch the request in the web service though.
My JavaScript function looks like so:
$(document).ready(
function () {
$(".sortable").sortable({
update: function () {
serial = $('.sortable').sortable('serialize');
$.ajax({
url: "MyWebService.asmx/SortTable",
type: "post",
data: serial,
error: function () {
alert("theres an error with AJAX");
}
});
}
});
});
The JSON string looks fine from what Firebug is showing me. The web service function is like so:
[WebMethod]
public string SortTable(String[] rows)
{
//SaveChanges();
return "Called!";
}
When I put a breakpoint in there, it never gets hit. When there are no arguments in the function though, it will get hit. I've tried replacing "String[]" with "object" and it still doesn't get hit, which I find odd. What is going on here?
You might need to decorate your web service with the [ScriptService] attribute in order to allow client scripts to invoke it. Also if you are sending a JSON request you need to specify the content type. Another remark is about sending the request as an actual JSON object which could be achieved using the JSON.stringify method (maybe the $('.sortable').sortable('serialize') call already does this, I am not familiar, you just need to ensure that the POSTed value looks like this: [ 'row1', 'row2', ... ]):
$.ajax({
url: 'MyWebService.asmx/SortTable',
type: 'post',
contentType: 'application/json; charset=utf-8',
data: JSON.stringify([ 'row1', 'row2', 'row3' ]),
error: function () {
alert('theres an error with AJAX');
}
});

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

jQuery Postback with Webforms

We're redevloping a major section of our website and rather than use a 90k AJAX file I'd rather use a 19K jquery script.
I've seen the following articles;
Using jQuery for AJAX with ASP.NET
Webforms
jQuery autocomplete in ASP.NET webforms?
Autocomplete with ASP.Net MVC and
JQuery
The thing I don't get is how to do a postback to a specific method in either the code behind or another class.
I know in ASP.NET-MVC I can post back to a controller / action. How do I call a particular method in WebForms?
Something along the lines of; $.post("class and action", ( param:value}......
Any thoughts, code etc???
It is very easy to call specific methods in code-behind. Here is nice article with all the details by Dave.
Simply declare a method like this:
[WebMethod]
public static string GetDate()
{
return DateTime.Now.ToString();
}
This is all you need in jQuery:
$.ajax({
type: "POST",
url: "PageName.aspx/MethodName",
data: "{}",
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function(msg, status, xhr) {
// Do something interesting here.
}
});
Caveats:
WebMethod must be on a static method
Must stringify posted data if sending anything (i.e. JSON.stringify(yourDataObject)), will be deserialized according to method parameters
msg is the response, the return result from your method is in the property msg.d

Categories