标签:razor asp-net javascript c asp-net-mvc
我有2个Index函数,
public ActionResult Index ( )
{
...
}
和
[HttpPost]
public ActionResult Index (HttpPostedFileBase file, string selectedOrgName, string selectedCatName)
{
...
}
第二种方法添加一个特定的对象:
ViewBag.orgcatJSON = PD.mapOrgs2Cats();
到ViewBag,而第一种方法则没有.如果调用了第二种方法,则需要使用Javascript对那个对象做一些事情.如果我调用了第一种方法,则不会.所以我在做的是
var ogmap = @Html.Raw(@ViewBag.orgcatJSON);
$(function() {
if (ogmap != undefined)
{
// do something
}
});
但这看起来很糟糕.有更好的方法吗?
解决方法:
如果您希望根据方法在视图中拥有不同的内容,则只需这样做并使用两个视图即可.然后,您可以将partials用于相关内容,以保持DRY的状态.
分离这样的视图的一个主要优点是,您已经使依赖关系(在这种情况下为ViewBag变量)更加清晰了.在您的示例中,您将不得不深入研究javascript以发现该细节,这可能需要一些时间.根据经验,我总是尝试使自己的观点尽可能愚蠢(即完成任务所需的逻辑尽可能少).
例如:
控制器/ExampleController.cs:
public ActionResult Index ( )
{
//...
return View("View1");
}
[HttpPost]
public ActionResult Index (HttpPostedFileBase file, string selectedOrgName, string selectedCatName)
{
//...
ViewBag.orgcatJSON = "some json string";
return View("View2");
}
视图/示例/View1.cshtml:
<h1>View 1</h1>
<!-- specific content here -->
<!-- now include shared content -->
@Html.Partial("SharedContent")
视图/示例/View2.cshtml:
<h1>View 2</h1>
<!-- specific content here -->
<!-- now include shared content -->
@Html.Partial("SharedContent")
<script>
var ogmap = @Html.Raw(ViewBag.orgcatJSON);
$(function() {
//functionality here
});
</script>
视图/示例/SharedContent.cshtml:
<p>Hello World!</p>
为了扩展更清晰的依赖点,您可以通过使用ModelBinder绑定期望的类型来使其更加清晰.这样,您的依赖项将更加隐蔽,您可以将ViewBag的用法替换为直接绑定的json.
有关ModelBinder是什么以及它如何工作的更多信息,建议您阅读this post.
如果决定走这条路线,请将第二个Index方法和第二个View更改为以下内容:
控制器/ExampleController.cs:
[HttpPost]
public ActionResult Index (HttpPostedFileBase file, string selectedOrgName, string selectedCatName)
{
//...
//let's pass the json directly to the View and make the dependency 100% clear
var json = "some json string";
return View("View2", json);
}
视图/示例/View2.cshtml:
@model System.String
<!-- in the above line, we are telling the view what type we expect to be bound by the controller -->
<h1>View 2</h1>
<!-- specific content here -->
<!-- now include shared content -->
@Html.Partial("SharedContent")
<script>
var ogmap = @Html.Raw(model);
$(function() {
//functionality here
});
</script>
标签:razor,asp-net,javascript,c,asp-net-mvc 来源: https://codeday.me/bug/20191028/1951373.html
本站声明: 1. iCode9 技术分享网(下文简称本站)提供的所有内容,仅供技术学习、探讨和分享; 2. 关于本站的所有留言、评论、转载及引用,纯属内容发起人的个人观点,与本站观点和立场无关; 3. 关于本站的所有言论和文字,纯属内容发起人的个人观点,与本站观点和立场无关; 4. 本站文章均是网友提供,不完全保证技术分享内容的完整性、准确性、时效性、风险性和版权归属;如您发现该文章侵犯了您的权益,可联系我们第一时间进行删除; 5. 本站为非盈利性的个人网站,所有内容不会用来进行牟利,也不会利用任何形式的广告来间接获益,纯粹是为了广大技术爱好者提供技术内容和技术思想的分享性交流网站。