具有多个变量的ASP.NET Actionlink为NULL

时间:2017-06-01 13:27:51

标签: c# asp.net-mvc html.actionlink

我正在尝试使用Html.Actionlink将2个变量发送到我的控制器,但每次我这样做时,我得到一个NULL值,而不是我想要发送的值。

这是我的Html.Actionlink:

<ul>
@{ Spot selectedSpot = (Spot)Session["SelectedSpot"];}
@foreach (Spot spot in (List<Spot>)Session["AllSpots"])
{
    if (selectedSpot != null)
    {
        if (selectedSpot.Id == spot.Id)
        {
            <li>@Html.ActionLink(spot.ToString(), "SetSpot", "EmsUser", new { selectedSpot = spot, user = Model }, new { @class = "selected"})</li>
        }
        else
        {
            <li>@Html.ActionLink(spot.ToString(), "SetSpot", "EmsUser", new { selectedSpot = spot, user = Model }, null)</li>
        }
    }
    else
    {
        <li>@Html.ActionLink(spot.ToString(), "SetSpot", "EmsUser", new { selectedSpot = spot, user = Model }, null)</li>
    }
}
</ul>

这是我的控制者:

public ActionResult SetSpot(Spot selectedSpot, User user)
    {
        Session["SelectedSpot"] = selectedSpot;
        user.SetId(0);
        return View("MakeReservation", user);
    }

编辑:

这就是actionlink对我的期望。 “EmsUser”是控制器名称,“SetSpot”是操作名称 enter image description here

1 个答案:

答案 0 :(得分:2)

我弄清楚问题是什么。 ActionLink中指定的路由参数作为查询字符串参数发布到控制器操作。您无法在路线参数中添加实例类型。如果你想传递物体,你将不得不做一些工作。请参阅下面的建议:

方法1: 在路由参数中单独传递类的所有字段。对于例如让我们说这些类是 -

public class Model1
{
    public int MyProperty { get; set; }
    public string MyProperty1 { get; set; }
}

public class Model2
{
    public int MyProperty2 { get; set; }
    public string MyProperty3 { get; set; }
}

你的ActionLink应该是:

@Html.ActionLink("Text", "SetSpot", "EmsUser",
new {
    MyProperty = 1,
    MyProperty1 = "Some Text",
    MyProperty2 = 2,
    MyProperty3 = "Some Text"
}, null)

方法2:

使用此link

中显示的ajax调用