[轉]How to add a script in a partial view in MVC4?

來源:互聯網
上載者:User

標籤:locate   and   ati   tty   oat   note   問題   asp.net   message   

本文轉自:https://stackoverflow.com/questions/14114084/how-to-add-a-script-in-a-partial-view-in-mvc4

 

問題:

This is the code which I have in my partial view

@model Contoso.MvcApplication.Models.Exercises.AbsoluteArithmetic@using(Html.BeginForm()){<div>    <span style="width: 110px; float:left; text-align:center; font-size:2.5em;">@Model.Number1</span>    <span style="width: 110px; float:left; text-align:center; font-size:2.5em;">+</span>    <span style="width: 110px; float:left; text-align:center; font-size:2.5em;">@Model.Number2</span>    <span style="width: 110px; float:left; text-align:center; font-size:2.5em;">=</span>    <span>            @Html.EditorFor(model => model.Result)            @Html.ValidationMessageFor(model => model.Result)    </span></div>}@section Scripts {    @Scripts.Render("~/bundles/jqueryval")}

Please note at the bottom of my code, I‘ve got a @section, and I realized that it‘s not running if I set a breakpoint there. If I move that line in the _Layout.cshtml it works well, but that‘s not the idea.

How can I tell to MVC4 in a partial razor view that I want to add that library?

 

 

 

 

參考答案:

 

This worked for me allowing me to colocate JavaScript and HTML for partial view in same file for ease of readability

In View which uses Partial View called "_MyPartialView.cshtml"

<div>    @Html.Partial("_MyPartialView",< model for partial view>,            new ViewDataDictionary { { "Region", "HTMLSection" } } })</div>@section scripts{    @Html.Partial("_MyPartialView",<model for partial view>,                   new ViewDataDictionary { { "Region", "ScriptSection" } }) }

In Partial View file

@model SomeType@{    var region = ViewData["Region"] as string;}@if (region == "HTMLSection"){}@if (region == "ScriptSection"){        <script type="text/javascript">    </script">}




另外關於 aspnetcore下的
How to use ViewDataDictionary with Html.Partial in asp.net core?

 

 

Another way to use this is to pass the ViewData of the current view into the constructor. That way the new ViewDataDictionary gets extended with the items you put in using the collection initializer.

@Html.Partial("MyPartial", new ViewDataDictionary(ViewData) { { "BookId", Model.Id } })

[轉]How to add a script in a partial view in MVC4?

相關文章

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.