将类的实例作为参数传递给Url.Action

时间:2019-09-25 19:51:16

标签: c# asp.net asp.net-mvc razor url-routing

我的目标是实现以下目标:

  1. 在ASP.NET页面上,用户从Server对象的列表中选择服务器。
  2. 用户单击按钮以导出有关该服务器的信息。
  3. 单击按钮会执行C#方法ExportServerInfo(),并将当前的Server对象(Model.Servers[i])传递给它。

控制器具有以下方法:

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=...>

单击按钮时,应使用选定的ExportServerInfo()作为唯一参数来调用ServerListController类中的方法Server。相反,由于Web服务器找不到用户,导致HTTP 404错误导致用户进入localhost:56789/ServerList/ExportServerInfo/ProjectName.ViewModels.Server。仅该字符串并不表示它是哪个服务器。根本不调用该方法。我尝试过的一种类似解决方案将用户带到空白页,而上述内容作为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传递回控制器。


此外,由于某种原因,该按钮在工作时外观还不错,但是在错误的实现方式下突出显示的颜色会有些许偏离。

tl; dr:参数未传递给该方法,该方法永不运行,用户被路由到404页。方法需要传递一个Server

1 个答案:

答案 0 :(得分:0)

不能将对象直接从视图传递到控制器。如果只有少量需要传递的属性,请将其作为类型声明器中的参数传递。

如果必须传递整个对象,请serialize the 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);
}