ASP.NET MVC- JSON ,Jquery, State management and Asynch controllers
一、JSON MVC And JQuery
In case you are new to JSON please read this before moving ahead with this lab ,What is JSON ?.So in this lab we will expose a simple “Customer” object from MVC in JSON format and consume the same using Jquery. For this lab please ensure that the project is created by using basic project template so that the necessary Jquery libraries are included with the MVC project.
Step 1 :- Create a simple Customer model
So the first step is to create a simple “Customer” class in the MVC project.
public class Customer
{
private string _CustomerCode;
public string CustomerCode
{
get { return _CustomerCode; }
set { _CustomerCode = value; }
}
}
Step 2 :- Expose Customer object as JSON
To expose the customer object in JSON format we need to use “JsonResult” as shown in the below code snippet.
public JsonResult getJson()
{
Customer obj = new Customer();
obj.CustomerCode = "c001";
return Json(obj,JsonRequestBehavior.AllowGet);
}
Please do once run the controller withthe above JSON action to check if the JSON result is displayed properly. If you are using chrome the display comes on the browser , if its internet explorer it spits out a file.
Step 3 :- Consume the JSON controller in jquery
In case you are new to Jquery , please read this What is jquery ?
The next step is to consume the JSON data in Jquery using MVC view. So go ahead and add a view for example my view name is “LearnJquery.aspx”.
First thing add the Jquery library at the top of the ASPX page. In case you do not find jquery library in your project that means you have not created the MVC project using the basic template.
<script src="../../Scripts/jquery-1.8.2.js"></script>
You can then make a call the controller which is exposing in JSON format using “getJson” method as shown below. Its takes three parameters
- The first parameter in “getJson” is the MVC JSON URL with complete controller/action path format.
- The second parameter is the data to be passed. For now its NULL as we are more interesting in getting JSON data rather posting data.
- The last parameter is the call back method (“Display”) which will be invoked once we get the JSON data from the controller. The “Display” function is also available in the below code snippet. I am just putting an alert with the property name. FYI you can see how I have just typed “data.CustomerCode” , no parsing nothing the JSON data is automatically translated to javascript object.
$.getJSON("/Json/getJson", null, Display);
function Display(data)
{
alert(data.CustomerCode);
}
The complete MVC view HTML looks as shown below. I have created a simple HTML button and on the click event I am calling a “getJson” javascript method which makes a call to the JSON controller and displays the JSON data in a javascript alert.
<script language="javascript">
function getJson() {
$.getJSON("/Json/getJson", null, Display);
return true;
}
function Display(data)
{
alert(data.CustomerCode);
}
</script>
<input type="button" value="See Json data" onclick="return getJson();"/>
This view I have invoked by using “DisplayJson” action.
public class JsonController : Controller
{
public ActionResult DisplayJson()
{
return View("LearnJquery");
}
}
Step 4 :- Run the application and see the data
After you have done all the hardwork its time to hit the “DisplayJson” action to see the beauty running.
二、Session management in MVC (ViewData,ViewBag,TempData and session variables)
The primary goal of MVC is to create web applications and web applications use HTTP protocol. Now HTTP protocol is a stateless by nature. So when you send a request to MVC application it serves the request and forgets about the request. Next time when the same user sends the request MVC treats that as a complete new request.
Now think about the below situation:-
- End user sends request to a MVC site.
- MVC sends a login page.
- User enters proper details and sends data to the MVC application.
- MVC validates the user and sends home page of the site. MVC application now forgets everything about the user as it’s stateless.
- Now user clicks on one of the home page links. This is sent to the MVC application and because MVC application has forgotten everything about the user, he sends a login page again for authentication….User would feel Weird…
In short we need to have some kind of mechanism which will help us to remember states between request and response of MVC.
There are 3 ways of maintaining states in MVC and these ways can be used depending from which layer to which layer you navigate.
Temp data: -Helps to maintain data on redirects for a single request and response. Now the redirects can be from controller to controller or from controller to view.
View data: - Helps to maintain data when you move from controller to view.
View Bag: - It’s a dynamic wrapper around view data. When you use “Viewbag” type casting is not required. It uses the dynamic keyword internally.
Session variables: - By using session variables we can maintain data until the browser closes.
Let’s demonstrate the above fundamental with a demo.
Step 1:- Create two controllers “DefaultController1” and “DefaultController2”.
Add two controllers “DefaultController1” and “DefaultController2”.
Step 2 :- Set Session , tempdata , viewdata and viewbag
In the “Default1Controller” in “Action1” we set session,tempdata,viewdata and viewbag values as shown in the below code snippet. Once we set the values we do a redirect to the action “SomeOtherAction” which belongs to “Controller2”.
public class Default1Controller : Controller
{
// GET: /Default1/
public ActionResult Action1()
{
Session["Session1"] = "UntilBrowserCloses";
TempData["FortheFullRequest"] = "FortheFullRequest";
ViewData["Myval"] = "ControllertoView";
ViewBag.MyVal = "ControllertoView";
return RedirectToAction("SomeOtherAction","Default2");
}
}
Step 3:- Read Session,tempdata ,viewdata and viewbag values
In “Default2Controller” we will try to read values set in “Default1Controller”. Once the values are read we invoke a view called as “SomeView”.
Please note I am setting “ViewData” and “ViewBag” before redirecting to the view.
public class Default2Controller : Controller
{
// GET: /Default2/
public ActionResult SomeOtherAction()
{
string str = Convert.ToString(TempData["FortheFullRequest"]);
string str2 = Session["Session1"].ToString();
string str3 = Convert.ToString(ViewData["Myval"]);
ViewData["Myval"] = "ControllertoView";
ViewBag.MyVal = "ControllertoViewCollection";
return View("SomeView");
}
}
The “SomeView”view justdisplays the data present in “TempData” ,”ViewData” , “ViewBag” and “Session” .
<%= TempData["FortheFullRequest"] %><br />
<%= ViewData["Myval"] %><br />
<%= Session["Session1"] %>
<%= ViewBag.MyVal %>
<a href="/Default1/Action1">Click</a>
So let’s put debug points in both the controller actions and let’s hit Default1 controller and Action1 actionhttp://localhost:1203/Default1/Action1 . So in this action session,tempdata ,viewdata and viewbag are loaded. Below is how the watch window looks with data.
Now from here we are redirecting to controller2 action “SomeOtherAction”.
In controller2 you can see get “TempData” and “Session” variables but not “ViewBag” and “ViewData”( See “str3” and “str4” are set to null). In other words “ViewData” and “ViewBag” do not persist data in redirects while “TempData” and “Session” variables do.
I have set “ViewData” and “ViewBag” with some data again before invoking the view “SomeView”.
When the view gets invoked we can see all the data. In other words “ViewData” and “ViewBag” persist data from controller to view. And also tempdata and session have persisted data.
Now when the view invokes I have kept a click hyper link which invokes “Action1” from “Controller1”. This is to simulate a fresh request.
When we click on the link. All the other variables go off only session variables persist, see the below figure. It means “Session” variables can persist between requests.
Below is a summary table which shows different mechanism of persistence.
Maintains data between | ViewData/ViewBag | TempData ( For single request) | Session |
Controller to Controller | NO | YES | YES |
Controller to View | YES | YES | YES |
View to Controller | NO | NO | YES |
ASP.NET MVC- JSON ,Jquery, State management and Asynch controllers的更多相关文章
- ASP.NET MVC使用jQuery来POST数据至数据库中
学习ASP.NET MVC程序,结合jQuery客户端代码,Post数据至数据库去.Insus.NET今天写一个完整性的例子. 在数据库中,创建一个表[dbo].[TestUser]: 既然是把数据存 ...
- asp.net mvc 接收jquery ajax发送的数组对象
<script type="text/javascript"> $(function () { var obj = { name: "军需品", m ...
- ASP.NET MVC使用jQuery实现Autocomplete
Insus.NET的以前的ASP.NET MVC的练习中,也有实现过Autocomplete的功能.依次是使用jQuery来实现. 首先在数据库准备一些数据: CREATE TABLE [dbo].[ ...
- ASP.NET MVC和jQuery DataTable整合
本文包含代码示例说明如何jQuery插件开发者可以集成到ASP.NET MVC应用程序. 下载源代码- 87.4 KB Introduction The jQuery DataTables plug- ...
- ASP.NET MVC 5 Jquery Validate
ClientValidationEnabled 在asp.net mvc 5中ClientValidationEnabled默认为TRUE,所以也不需要刻意去设置 应用ValidationAttrib ...
- ASP.NET MVC之Session State性能问题(七)
前言 这一节翻译一篇有关Session State性能问题的文章,非一字一句翻译. 话题 不知道我们在真实环境中是否用到了Session State特性,它主要用来当在同一浏览器发出多个请求时来存储数 ...
- Asp.NET MVC JSON序列化问题
最近在做项目的时候遇到一个JSON序列化问题. 环境:ASP.NET MVC 4.0 数据库:SQL 2008 在将获取的数据从后台以json的形式传给前台的easyui treegrid绑定的时候通 ...
- ASP.NET MVC使用jQuery无刷新上传
昨晚网友有下载了一个jQuery无刷新上传的小功能,他尝试搬至ASP.NET MVC应用程序中去,在上传死活无效果.Insus.NET使用Teamviewer远程桌面,操作一下,果真是有问题.网友是说 ...
- ASP.NET MVC中jQuery与angularjs混合应用传参并绑定数据
要求是这样子的,在一个列表页中,用户点击详细铵钮,带记录的主键值至另一页.在另一外页中,获取记录数据,然后显示此记录数据在网页上. 先用动图演示: 昨天有分享为ng-click传递参数 <ang ...
随机推荐
- DJANGO:从当前用户的所属用户组里查找其所拥有的权限矩阵
没办法,随时项目越来越精进,要求也越来越多. 以前的权限精度已满足不了现在的要求, 那就设计一个权限矩阵,用HOOK返回来判断吧... [莫名其妙的ORM,留个念想] 主要是在表之间的跳转,要注意语法 ...
- linux登录后出现_bash-4.1#终端提示符异常
如果使用root用户登录出现上述提示,则需要需要重建 /root .bash_profile文件: 1. vi /root .bash_profile 2. 输入如下内容 # .bashrc # Us ...
- easyui源码翻译1.32--DateBox(日期输入框)
前言 扩展自$.fn.combo.defaults.使用$.fn.datebox.defaults重写默认值对象.下载该插件翻译源码 日期输入框结合了一个可编辑的文本框控件和允许用户选择日期的下拉日历 ...
- Android HttpClient get传递数组
url请求格式: String url = "http://10.80.7.26:" + +;
- Django单元测试(二)------测试工具
The test client test client是一个python类,来模拟一个简单的“哑”浏览器,允许你来测试你的view函数.你可以使用test client完成下列事情: 1.模拟&quo ...
- linux进程间通信方式
(1)管道(Pipe):管道可用于具有亲缘关系进程间的通信,允许一个进程和另一个与它有共同祖先的进程之间进行通信. (2)命名管道(named pipe):命名管道克服了管道没有名字的限制,因此,除具 ...
- bzoj2565
网络流就先告一段落了 在进行其他训练之前,我决定先练一道后缀数组(对这个我还是比较有自信的) 虽然之前没用后缀数组解决过回文问题,但是稍微想想就知道, 要解决最长双倍回文,首先要解决最长回文序列, 要 ...
- C#中的try catch finally
try中的程序块是有可能发生错误的程序块,catch中的程序块是当发生错误的时候才会执行的代码块,finally中的程序块是无论是否发生错误都会执行的代码块. 示例程序: ? 1 2 3 4 5 6 ...
- c#中Lock(锁)的研究以及跨线程UI的操作
本文只针对C#中,多线程同步所用到的锁(lock)作为研究对象.由于想更直观的显示结果,所以,在做demo的时候,就把多线程通过事件操作UI的代码也写了出来,留作备忘和分享吧. 其实多线程 ...
- SharePoint : 使用SPQuery对象时要注意的事项
转:http://www.cnblogs.com/chenxizhang/archive/2009/10/23/1588415.html 我们经常需要对一个列表进行查询,此时最灵活的方式就是直接使用S ...