返回一个PartialView既HTML和JavaScript [英] Returning a PartialView with both HTML and JavaScript

查看:161
本文介绍了返回一个PartialView既HTML和JavaScript的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想提出一个AJAX调用(用jQuery)检索 PartialView 。随着HTML我想发送回浏览正在显示该对象的JSON重新presentation。我一直在使用蹩脚的方式是在HTML中,它很快就会变得笨拙,紧密结合了太多的东西,隐藏的输入嵌入属性。

I am making an AJAX call (with jQuery) to retrieve a PartialView. Along with the HTML I'd like to send back a JSON representation of the object the View is displaying. The crappy way that I've been using is embedding properties as hidden inputs in the HTML, which quickly becomes unwieldy and tightly couples far too much stuff.

我可以只发送的JavaScript在<脚本>将HTML后标签,但我真的很肛门约维持这些东西分开。这将是这样的:

I could just send the JavaScript in a <script> tag after the HTML, but I'm really anal about keeping those things separate. That would look like this:

<%@ Control Language="C#" AutoEventWireup="true" Inherits="System.Web.Mvc.ViewUserControl<Person>" %>
<div class="person">
  First Name: <%= Html.TextBox("FirstName", Model.FirstName) %>
  Last Name: <%= Html.TextBox("LastName", Model.LastName) %>
</div>
<script type="text/javascript">
  // JsonSerialized object goes here
</script>

我考虑的另一个选择是进行第二次AJAX调用返回一个动作 JsonResult ,但也感觉不好的设计。

Another option I considered is to make a second AJAX call to an action that returns JsonResult, but that also feels like bad design.

推荐答案

我想我找到了一个pretty的好办法做到这一点,只是包装的 JSON 起来在的HtmlHelper 扩展。下面是类:

I think I found a pretty good way to do this, just wrap the JSON up in an HtmlHelper extension. Here's the class:

using System.Web.Script.Serialization;

public static class JsonExtensions {
    public static string Json(this HtmlHelper html, string variableName) {
        return Json(html, variableName, html.ViewData.Model);
    }

    public static string Json(this HtmlHelper html, string variableName, object model) {
        TagBuilder tag = new TagBuilder("script");
        tag.Attributes.Add("type", "text/javascript");
        JavaScriptSerializer jsonSerializer = new JavaScriptSerializer();
        tag.InnerHtml = "var " + variableName + " = " + jsonSerializer.Serialize(model) + ";";
        return tag.ToString();
    }
}

和您通过调用它:

<%= Html.Json("foo") %>
<%= Html.Json("bar", Model.Something) %>

在一个陷阱,我能想到的是,它并不是一个完全的完美的分离;你还在技术上投入的JavaScript的HTML。 但是的,它没有到服务器的额外调用,并在IDE的标记还是很干净的。

The one catch that I can think of is that it isn't a completely perfect separation; you are still technically putting JavaScript in the HTML. But, it doesn't make an extra call to the server, and the markup in the IDE is still very clean.

这篇关于返回一个PartialView既HTML和JavaScript的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆