900字范文,内容丰富有趣,生活中的好帮手!
900字范文 > mvc5 返回html 在asp.net mvc中使用PartialView返回部分HTML段

mvc5 返回html 在asp.net mvc中使用PartialView返回部分HTML段

时间:2022-06-14 03:59:25

相关推荐

mvc5 返回html 在asp.net mvc中使用PartialView返回部分HTML段

该问题是个常见的 case, 故写篇文章用于提示新人。

相信聪明的你已经知道了它俩的区别了,没错 一个用于返回整体,另一个返回局部(部分)。

假设我有这样一个需求,输入用户名,然后返回相关信息。之前的做法可能会是用json格式来返回用户的相关信息,然后到页面去渲染相关

的HTML,如果产生的相关HTML比较大的话,我还是建议你沿用之前的方案(返回json),因为传输的数据少,响应快一些。

Layout.cshtml

html>

@ViewBag.Title

@RenderBody()

Index.cshtml

@{

ViewBag.Title ="Index";

Layout ="~/Views/Shared/_Layout.cshtml";

}

PartialView Demo

Please write your name here

$(function() {

$('#btnOK').click(function() {

vardata = { Name: $('#txtName').val()};

$.ajax({

type:"POST",

url:'@Url.Action("PartialViewDemo","Home")',

data: data,

datatype:"html",

success:function(data) {

$('#content').html(data);

},

error:function() {

alert("处理失败!");

}

});

});

});

ViewUserControl.cshtml(Partial View)

@modelSample.Models.PartialViewDemoViewModel

ViewUserControl.cshtml

@Model.dt

Hello~@Model.Name

orViewUC.ascx(View User Control)

"%>

ViewUC.ascx

Hello~

Model

publicclassPartialViewDemoViewModel

{

publicstringName {set;get; }

publicDateTime? dt {set;get; }

}

Action

[HttpPost]

publicActionResultPartialViewDemo(PartialViewDemoViewModelmodel)

{

model.dt =DateTime.Now;

returnPartialView("ViewUserControl", model);

//return PartialView("ViewUC", model);

}

调用Controller.PartialView方法时,可以指定Partial VieworView User Control效果是一样的

不写后缀时,会查找同目录和Shared目录下的文件,也就是在同目录或Shared目录下时可以省略后缀名。

如果目录下存在同名的情况,会找第一个并返回。

eg:同目录下有ViewUserControl.ascx和ViewUserControl.cshtml

这时使用returnPartialView("ViewUserControl");

会返回ViewUserControl.ascx的内容,因为字母a在c前:)

如果在这种情况下想调用ViewUserControl.cshtml

则需要写全路径,returnPartialView("~/Views/Home/ViewUserControl.cshtml");

当想访问的Partial VieworView User Control在不同目录时,也可以通过全路径的方式访问。

本内容不代表本网观点和政治立场,如有侵犯你的权益请联系我们处理。
网友评论
网友评论仅供其表达个人看法,并不表明网站立场。