惯性聚合 高效追踪和阅读你感兴趣的博客、新闻、科技资讯
阅读原文 在惯性聚合中打开

推荐订阅源

小众软件
小众软件
IT之家
IT之家
博客园 - 聂微东
www.infosecurity-magazine.com
www.infosecurity-magazine.com
P
Privacy International News Feed
人人都是产品经理
人人都是产品经理
PCI Perspectives
PCI Perspectives
OSCHINA 社区最新新闻
OSCHINA 社区最新新闻
博客园 - 叶小钗
V
Vulnerabilities – Threatpost
美团技术团队
S
Secure Thoughts
N
News | PayPal Newsroom
L
LINUX DO - 最新话题
腾讯CDC
Application and Cybersecurity Blog
Application and Cybersecurity Blog
雷峰网
雷峰网
B
Blog
MyScale Blog
MyScale Blog
T
The Blog of Author Tim Ferriss
TaoSecurity Blog
TaoSecurity Blog
N
News and Events Feed by Topic
Blog — PlanetScale
Blog — PlanetScale
C
Check Point Blog
T
Tailwind CSS Blog
月光博客
月光博客
Simon Willison's Weblog
Simon Willison's Weblog
Hacker News: Ask HN
Hacker News: Ask HN
The Last Watchdog
The Last Watchdog
Google DeepMind News
Google DeepMind News
cs.CV updates on arXiv.org
cs.CV updates on arXiv.org
MongoDB | Blog
MongoDB | Blog
S
Security @ Cisco Blogs
Jina AI
Jina AI
Engineering at Meta
Engineering at Meta
S
Security Affairs
Forbes - Security
Forbes - Security
P
Palo Alto Networks Blog
cs.CL updates on arXiv.org
cs.CL updates on arXiv.org
博客园 - 司徒正美
博客园 - 三生石上(FineUI控件)
T
Tor Project blog
O
OpenAI News
L
Lohrmann on Cybersecurity
Security Archives - TechRepublic
Security Archives - TechRepublic
P
Proofpoint News Feed
Cyber Security Advisories - MS-ISAC
Cyber Security Advisories - MS-ISAC
L
LangChain Blog
B
Blog RSS Feed
H
Hackread – Cybersecurity News, Data Breaches, AI and More

博客园 - vito qi

安装VS2015出现的bug,各位安装请注意 苹果编程语言Swift简介 设计模式之三职责链模式 HTML页面做中间页跳转传递参数 第一个 ASP.NET Web API应用程序 ASP.NET应用程序与页面生命周期 自定义服务器控件ImageButton 成功项目经理的三种领导力行为 设计模式之二抽象工厂设计模式 深入理解C#之 参数传递 ref out params ASP.NET 实现文件下载 C#实现根据IP 查找真实地址 IIS 7.0的集成模式和经典模式 ASP.NET 4.0: 请求验证模式变化导致ValidateRequest=false失效 设计模式之—简单工厂设计模式 ASP.NET MVC 学习笔记(一) 数据库分离附加工具 c# 新特性 c#总结(一)
ASP.NET MVC中 Jquery AJAX 获取数据利用MVC模型绑定实现输出
vito qi · 2012-08-29 · via 博客园 - vito qi

     在日常项目中我们经常使用ajax ,无论是webform 还是mvc ,jQuery确实是一个挺好的轻量级的JS框架,能帮助我们快速的开发JS应用,并在一定程度上改变了我们写JavaScript代码的习惯。jquery ajax 为我们实现ajax提供了一些非常方便的实现ajax的方法。我们利用ajax返回到前台的json字符串,需要我们自己去处理解析,很多时候我们需要自己手动的去拼html 字符串 很麻烦,那么有没有简单的方法呢,在MVC中,提供了一种机制模型绑定。

     在ASP.net MVC中,使用了一种称之为“模型绑定”的机制,将模型对象与HTTP请求的数据通过Action方法的参数进行映射绑定,无论从简单的数据或者到复杂的数据结构,应付模型绑定的一切工作,MVC框架都能游刃有余。在ajax的应用中,我们如何利用这个特性呢,我们可以把数据通过模型绑定 把数据绑定到视图,然后再获取视图输出的字符串,直接输出即可。

我们首先定义一个ApplicationController 继承 Controller 。在ApplicationController中定义如下:

 1  public class ApplicationController : Controller
 2     {
 3         protected string RenderPartialViewToString(string viewName, object model)
 4         {
 5             if (string.IsNullOrEmpty(viewName))
 6                 viewName = ControllerContext.RouteData.GetRequiredString("action");
 7 
 8             ViewData.Model = model;
 9 
10             using (var sw = new StringWriter())
11             {
12                 ViewEngineResult viewResult = ViewEngines.Engines.FindPartialView(ControllerContext, viewName);
13                 var viewContext = new ViewContext(ControllerContext, viewResult.View, ViewData, TempData, sw);
14                 viewResult.View.Render(viewContext, sw);
15 
16                 return sw.GetStringBuilder().ToString();
17             }
18         }
19 
20     }


我们只需要传入视图名称,和实体数据,就可以输出我们定义好格式的字符串。

定义控制器 继承 ApplicationController

 1  public class HomeController : ApplicationController
 2     {
 3         private static Users _usrs = new Users();
 4  
 5         public ActionResult Index()
 6         {
 7             return View(_usrs._usrList);
 8         }
 9 
10         public ActionResult Create()
11         {
12             return View();
13         }
14 
15         [HttpPost]
16         public ActionResult Create(UserModel item)
17         {
18             _usrs.Create(item);
19             return View();
20         }
21 
22         public ActionResult Edit(string id)
23         {
24             return View(_usrs.GetUser(id));
25         }
26 
27         [HttpPost]
28         public ActionResult Edit(UserModel um)
29         {
30             _usrs.Update(um);
31             return View();
32         }
33 
34         public ActionResult About()
35         {
36             return View();
37         }
38 
39         public ViewResult Delete(string id)
40         {
41             return View(_usrs.GetUser(id));
42         }
43 
44         [HttpPost]
45         public RedirectToRouteResult Delete(string id, FormCollection collection)
46         {
47             _usrs.Remove(id);
48             return RedirectToAction("Index");
49         }
50 
51         public JsonResult Details(string id)
52         {
53             UserModel user = _usrs.GetUser(id);
54             var m = new { Status = 1, Message = "Ok", Content = RenderPartialViewToString("Details", user) };
55             return Json(m);
56         }
57       
58 
59     }


Details 方法中 我们返回一个JsonResult,调用了RenderPartialViewToString 方法。

Details 视图中定义:

   <h2>Details</h2>

    <fieldset>
        <legend>Fields</legend>
        <div class="display-label">UserName</div>
        <div class="display-field">@Model.UserName</div>
        
        <div class="display-label">FirstName</div>
        <div class="display-field">@Model.FirstName</div>
        
        <div class="display-label">LastName</div>
        <div class="display-field">@Model.LastName</div>
        
        <div class="display-label">City</div>
        <div class="display-field">@Model.City</div>
    </fieldset>

    <p>
    @Html.ActionLink("Edit", "Edit", new {  id=@Model.UserName }) |
        @Html.ActionLink("Back to List", "Index")
    </p>

客户端js写法(必须引入jquery文件):

<script language="javascript" type="text/javascript">
    function showDetails(id) {
        $.post("/Home/Details?id=" + id, function (data) {
            if (data.Status <= 0) {
                alert(data.Message);
                return;
            }
            $("#detailsinfo").html(data.Content);
        });
        }

</script>


运行结果:

直接上代码:

 点我下载