簡體   English   中英

如何將字符串值從Controller方法獲取到View腳本標簽變量?

[英]How to get string value from Controller method to a View script tag variable?

例如,我在控制器內部有一個方法

private string GetString()
{
    return "Hi string";
}

然后在<script>標簽內的View中變量:

<script> let str = ""; </script>

如何從控制器中的方法獲取字符串?

<script> let str = Controller.GetString(); </script>

特拉維斯為此提供了幫助:

@using ThrowAwayWeb.Helper;

<h2>Index</h2>
<h2>@ViewHelpers.GetString()</h2>
<script>let str = @ViewHelpers.GetString();</script>

但是JavaScript正在編碼字符,在這種情況下,需要做一些改動

<script>let str = @Html.Raw(@ViewHelpers.GetString());</script>

我也找到了有趣的選擇,將Razor調用放在雙引號中:

<script>let str = "@Html.Raw(@ViewHelpers.GetString());"</script>

除了Kei的出色答案(涵蓋大多數情況下最合適的用法)外,還有另一個選擇:

創建一個靜態類:

    namespace ThrowAwayWeb.Helper
    {
        public static class ViewHelpers
        {
            public static string GetString() { return "Hi String"; }
        }
    }

直接在您的視圖中加載並使用它:

    @using ThrowAwayWeb.Helper;


    <h2>Index</h2>
    <h2>@ViewHelpers.GetString()</h2>
    <script>let str = @ViewHelpers.GetString();</script>

我不認為可以直接從視圖中調用控制器方法。 相反,這是三種替代方法。

方法1:將方法移至模型

模型類

public class SomeModel
{
    public string GetString() 
    {
        return "Hi string";
    }
}

視圖

@model SomeModel   
// The above should be on the first line.

// Script portion of the view
<script> let str = "@Model.GetString()"; </script>

方法2:通過ViewData(或ViewBag)將數據從控制器傳遞到視圖

調節器

public ActionResult Index()
{
    // The key, "GetStringResult" is arbitrary. 
    // Whatever value you assign to this key can be accessed from the view using the same key.
    ViewData["GetStringResult"] = GetString();
    return View();
}

private string GetString() 
{
    return "Hi string";
}

視圖

<script> let str = '@ViewData["GetStringResult"]'; </script>

方法3:將Controller上的方法轉換為Public Action,並通過AJAX檢索結果

調節器

public ActionResult GetString()
{
    return "Hi string";
}

視圖

<script> 
    let str = "";
    // Using jQuery
    // Note that str will only get set after the request is done.
    $.get(@Url.Action("GetString", "ControllerName")).done(function(data) {
        str = data;
    });
</script>

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM