簡體   English   中英

將 class 的實例作為參數傳遞給 Url.Action 的操作/方法

[英]Passing an instance of a class as an argument to the action/method of Url.Action

我的目標是實現以下目標:

  1. 在 ASP.NET 頁面上,用戶從Server對象列表中選擇一個服務器。
  2. 用戶單擊按鈕以導出有關該服務器的信息。
  3. 單擊該按鈕執行 C# 方法 ExportServerInfo ExportServerInfo()並將當前Server object ( Model.Servers[i] ) 傳遞給它。

controller有方法:

public void ExportServerInfo(Server id)
{
    // Do something with the Server
    System.Diagnostics.Debug.WriteLine(id.Name);
    System.Diagnostics.Debug.WriteLine(id.RamCapacity);
}

該視圖是一個使用 Razor 的 CSHTML 文件。 這是按鈕的代碼:

<div class="col-md-12" align="right">
    <a href="@Url.Action("ExportServerInfo", "ServerList", new { id = Model.Servers[i] })" class="btn btn-primary">
        <span class="glyphicon glyphicon-download-alt" aria-hidden="true"></span>
         @MainResource.SomeLocalizationString
    </a>
</div>

HTML 生成: <a href="/ServerList/ExportServerInfo/ProjectName.ViewModels.Server" class=...>

單擊按鈕時,應調用 ServerListController class 中的方法 ExportServerInfo ExportServerInfo() ,並將所選Server作為唯一參數。 相反,用戶被帶到localhost:56789/ServerList/ExportServerInfo/ProjectName.ViewModels.Server並出現來自 web 服務器的 HTTP 404 錯誤,因為它找不到它; 該字符串本身並不能指示它是哪個服務器。 該方法根本沒有被調用。 我嘗試過的類似解決方案將用戶帶到一個空白頁面,並將上述內容作為 URL 中的查詢字符串。

當用戶單擊按鈕時,應該調用該方法,但相反,用戶被移動到一個頁面(404s)並且該方法沒有被調用。


如果操作沒有參數/參數,則執行該方法:

<div class="col-md-12" align="right">
    <a href="@Url.Action("ExportServerInfo", "ServerList")" class="btn btn-primary">
        <span class="glyphicon glyphicon-download-alt" aria-hidden="true"></span>
         @MainResource.SomeLocalizationString
    </a>
</div>

HTML 生成: <a href="/ServerList/ExportServerInfo" class=...>

用戶單擊按鈕(“訪問” /ServerList/ExportServerInfo )但停留在頁面上,並且該方法運行(沒有參數)。 但是該方法必須有一個參數才能將Server傳回controller。


此外,由於某種原因,按鈕的外觀在它工作時很好,但是由於錯誤的實現,突出顯示的顏色有點偏離。

tl; dr:參數未傳遞給方法,方法永遠不會運行,用戶被路由到 404 頁面。 方法需要一個Server傳遞給它。

object 不能直接從視圖傳遞到 controller。 如果您只有幾個屬性需要傳遞,請在類型聲明器中將它們作為 arguments 傳遞。

如果您必須傳遞整個 object,請序列化 object並將其作為字符串參數傳遞。

<div class="col-md-12" align="right">
    <a href="@Url.Action("ExportServerInfo", "ServerList", new { s = Newtonsoft.Json.JsonConvert.SerializeObject(Model.Servers[i] })" class="btn btn-primary">
        <span class="glyphicon glyphicon-download-alt" aria-hidden="true"></span>
         @MainResource.SomeLocalizationString
    </a>
</div>

調整該方法,使其接收一個字符串,然后對其進行反序列化並將其存儲在對象原始類型的變量中。

public void ExportServerInfo(string s)
{
    Server server = Newtonsoft.Json.JsonConvert.DeserializeObject<Server>(s);

    // Do something with the Server
    System.Diagnostics.Debug.WriteLine(server.Name);
    System.Diagnostics.Debug.WriteLine(server.RamCapacity);
}

暫無
暫無

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

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