How does ASP.NET MVC Data Binding work without reloading webpage? - c#

I've just started using ASP.NET MVC 4.0 to build a web application. I've been through the tutorials that explain and demonstrate View/Controller/Models, but now I'm wanting to go a step further.
Instead of having all of my pages constantly reload as users interact with my application, i'd like to learn how to make async calls to the server side to load data.
A great example of what I would like to learn how to implement is:
http://demo.aspnetawesome.com/AjaxDropdownDemo/Index
The Drop Downs are bound to each other, and the page never refreshes. Does anyone have some suggestions on where I can go to learn how to begin learning this? Also, since I am using MVC how can I use Model Binding to help make it more simple?

To Make and async calls to your action you can make ajax call as follows
Jquery Code:
var AsyncCall = function () {
$.ajax({
type: "POST",
url: "Home/Index",
data: JSON.stringify(yourData),
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (result) {
// Success implementation
},
error: function () {
}
});
};
In Controller :
[HttpPost]
public ActionResult Index(DataType model)
{
// Implementation
return View(model);
}

Related

Asp net mvc 5 add security to a jsonresult?

So I have this application that´s almost finished but i need to add now some extra security and since i am not too familiar with some of Asp.Net mvc 5 methods I have this question.
Is it possible to add some sort of encryption or something similar to a jsonresult? The idea is if I have sensitive information being sent through json is there anything I can add server side to secure it or does MVC5 take care of that already?
here is a very basic example
$.ajax({
type: "POST",
url: 'GetImptInfo',
data: { 'Something': Something, 'Something2': Something2}, //this can be anything
dataType: "json",
success: function (result) {
alert('Added');
//do stuff
},
error: function (xhr, ajaxOptions, thrownError) {
//some errror, some show err msg to user and log the error
alert(xhr.responseText);
}
});
the controller method
public JsonResult GetImptInfo(int Something, int Something)
{
//get stuff from the server
var imptInfo = RequestInfo();
return Json(impInfo, JsonRequestBehavior.AllowGet);
}
Is there anything I can add in order to secure that json or is what I have enough?
You can use a secured protocol to transport your information i.e https. You can also have a look at this link to see why JsonResult is needed:
Why is JsonRequestBehavior needed?

Call code-behind function from javascript in visual webpart

Is it even possible? To call a code-behind c# function from javascript in a visual web part?
It is a complex function so converting all my codes to client side is not an option. I want the logic that is there in this function to happen without a page refresh. This is the background of my issue.
Thanks guys..
You can use jQuery ajax to call server side method and get the response to be used in javascript. This article has simple and good example to show what you need to do.
Code behind
public partial class _Default : Page
{
[WebMethod]
public static string GetDate()
{
return DateTime.Now.ToString();
}
}
Javascript
$.ajax({
type: "POST",
url: "PageName.aspx/MethodName",
data: "{}",
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function(msg) {
// Do something interesting here.
}
});
Why don`t you use a Webservice (Ajax-Enabled WCF Service) which can be called via AJAX?
I think this would be the clean way. Put your logic in an extra class and use this class in the webservice and your webpart. Then you cann call the Method from Code and from Javascript.

Page Methods and Security

Recently I learned that you can take a script manager and set the EnablePageMethods="true" this is something I would like to do but is there any security implications ?
Also, Is there a newer better way to this ?
All that EnablePageMethods="true" really does is generate an inline JavaScript proxy that allows for calling back to ASP.NET AJAX Page Methods via the PageMethods syntax.
I prefer using jQuery via its .ajax() method to call ASP.NET AJAX Page Methods, like this:
Code-behind
[WebMethod]
public static string GetDate()
{
return DateTime.Now.ToString();
}
JavaScript:
$.ajax({
type: "POST",
url: "PageName.aspx/GetDate",
data: "{}",
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function(msg) {
// Do something interesting here.
}
});
Note: Since ASP.NET AJAX Page Methods automatically serialize their response to JSON, then "json" is the return dataType of the AJAX call. contentType describes what you are sending to the server.
It does not have any more security implications than would adding any ordinary web page or service to a website. The needed precautions are the same -- don't use any inputs without validating them first, don't inadvertently return sensitive information in error messages, etc.
There is a newer way, and arguably better, if you don't mind switching to a new platform: ASP.Net MVC, and the related "Web API". (You can use Web API with Webforms also, thanks to Karl Anderson for noting in the comments.)

Calling a function in the .aspx.cs code behind file with jQuery load()

So I have something like this situation:
$(document).on('click', 'a[data-link]', function () {
var $this = $(this);
url = $this.data('link');
$("#imagePreview").load("imageProcess.aspx?" + url);
where url holds GET parameters. But imageProcess.aspx is different than the file I'm in (dashboard.aspx) and I need to reference some panels within my dashboard.aspx file. So my question is, using the .load() function, or even any function that could get the job done, how do I call a function, with GET parameters, in the dashboard.aspx code behind file? I'm fairly new to the .NET framework so I apologize if the question sounds elementary.
In your imageProcess.aspx.cs create a webmethod like:
[WebMethod]
public static string YourMethod(your parameters)
{
//Do Your Work
}
and in your dashboard page, in javascript use jquery to send request your webmethod like:
$.ajax({
type: "POST",
url: "imageProcess.aspx/YourMethod",
data: "{parameter1Name:'" + JSON.stringify(parameter1value) + "', Parameter2Name:'" + JSON.stringify(parmeter2Value) + "'}",
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function(data) {
// do your success work, keep in mind that your returned data will be in data.d
},
error: function(XMLHttpRequest, textStatus, errorThrown) {
// do your failuer work
}
});
I hope it will give you a guidance to achieve your task.
Just to make sure: You are trying to access functionality from a different aspx page than the one you are currently on.
I'm not entirely sure if you can do that the easy way by java script. Maybe someone else knows a better way, but the way I would do it is creating ashx service page which will handle your request so you can provide the data you need (in your case an image)
For more information see http://www.dotnetperls.com/ashx

How to call a function repeatedly with 5 seconds delay? (ASP.NET with C#)

I have a some piece of code in Default.aspx.cs file which is written within Page_Load function like this:
protected void Page_Load(object sender, EventArgs e)
{
//code stars here
...
//code ends here
}
What i want is that this piece of code will run continously with 5 seconds delay. How can I do this here?
Thank You.
Looking at your comments I see your actually building a chat facility, which makes more sense regarding the continous requests every 5 seconds.
I would recommend using ASP.NET Web Methods and AJAX technology to achieve this.
Using jQuery.ajax you can make a request every 5 seconds in javascript to return new chat messages
Something like the following would be a good start for your javascript/jquery:
setInterval(function () {
$.ajax({
url: "/Chat.asmx"
, type: "POST"
, contentType: 'application/json; charset=utf-8'
, data: '{ ConversationID: "' + ConversationID + '"}'
, dataType: 'json'
, success: function (data) {
//do something with data
}
});
}, 5000);
Chat.asmx would then be your Web Method. Look into ASP.NET Web Methods for more info:
http://encosia.com/using-jquery-to-directly-call-aspnet-ajax-page-methods/
A quicker method, but not as recommended, would be to use jQuery.load where you could have the chat messages in a repeater on a standalone .aspx page and keep loading this into a div on your page like:
setInterval(function () {
$(".chatmessages").load("ChatConversation.aspx?id=" + ConversationID);
}, 5000);
See jQuery.load for more info on this
As the others suggest, use ajax and get your data from the clietn every 5 seconds.
Here is a small sample which should get you started.
You need to include the jQuery javascript framework for this to work.
Clientside javascript:
// execute this on dom ready
$(document).ready(function () {
// call function getData every 5 seconds:
setInterval("getData()", 5000);
});
// Call an asp PageMethod via an ajax call
function getData() {
$.ajax({
type: "POST",
async: true,
contentType: "application/json; charset=utf-8",
url: "YourPage.aspx/GetData",
// optional post some data
// data: JSON.stringify(data),
success: dataReceived
});
}
// callback function is called, when data is recevied
function dataReceived(data, textStatus, jqXHR) {
// your data is in data.d
}
On the serverside you have to write a "page method" in your aspx page wich is a static method you can call by an ajax javascript call:
public class YourPage : Page
{
[WebMethod]
public static object GetData() {
// return your data here
return new {Data1 = ..., Data2 = ...};
}
}
You can pass data to your page method by parameters. The names of the parameters have to match exactly the names of the json object properties you pass to $.ajax.
From your edit, building a chat application would require more than just the page running a repeated task every 5 seconds.
For a simple chat, you could achieve this using AJAX and the setInterval() method in Javascript, but doing so could tie up all threads with an HTTP server such as Apache.
More prudent chats would make use of a distinct HTTP server created in many technologies, you might look into emerging technologies such as socket.io based on node.

Categories

Resources