【发布时间】:2017-06-12 16:39:44
【问题描述】:
我想在主页类型视图上预览一个视图。为此,我想调用 ListPreviews Action。我希望此操作获取给定视图的 html 正文,然后获取前一百个字符左右。
如何从控制器访问视图的实际 html?
【问题讨论】:
-
您能告诉我如何进一步帮助您吗?
标签: html asp.net-mvc view controller preview
我想在主页类型视图上预览一个视图。为此,我想调用 ListPreviews Action。我希望此操作获取给定视图的 html 正文,然后获取前一百个字符左右。
如何从控制器访问视图的实际 html?
【问题讨论】:
标签: html asp.net-mvc view controller preview
这应该很简单。 在您的 RouteConfig.cs 中设置默认值,我的看起来像这样:
defaults: new { controller = "Home", action = "Index2006", id = UrlParameter.Optional }
对于您的控制器/模型:
public class AView
{
public string theHtml { get; set; }
}
public class HomeController : Controller
{
[HttpPost]
public ActionResult Index2005(AView AView)
{
//put breakpoint here to see all the <html> here in view
var result = HttpUtility.UrlDecode(AView.theHtml, System.Text.Encoding.Default);
return Json(new
{
Greeting = "Returning data not used"
}
, @"application/json");
}
供您参考:
<!DOCTYPE html>
<html id="PassMe">
<head>
<meta name="viewport" content="width=device-width" />
<title>Index2005</title>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.4/jquery.min.js"></script>
<script type="text/javascript">
$(function () {
$(".btn").click(function () {
var AView = { theHtml: escape($("#PassMe").html()) }; //JSON.stringify($("#PassMe").html())
$.ajax({
url: '/Home/Index2005',
type: 'POST',
data: AView,
success: function (result) {
$("#detail").append(result.Greeting);
},
error: function (result) {
alert('Error');
}
});
});
});
</script>
</head>
<body>
<button style="margin-bottom: 20px;" class="btn btn-default">Click to pass HTML</button>
</body>
</html>
【讨论】: