简体   繁体   English

Html.ActionLink没有通过值

[英]Html.ActionLink not passing through value

I am trying to pass through a value from my view to my controller based on what I click on, using HTML.ActionLink. 我试图根据我点击的内容,使用HTML.ActionLink将视图中的值传递给我的控制器。 For example, if I click on 'Soccer' then I want the value 'Soccer' to be passed to the controller, which will then change what is being displayed. 例如,如果我单击“足球”,那么我希望将值“足球”传递给控制器​​,然后控制器将更改正在显示的内容。 Currently when I click on the sport name nothing happens, and when I debug the project, the sport name parameter in the controller is null, which means that the value has not been passed to the controller. 目前当我点击运动名称时没有任何反应,当我调试项目时,控制器中的运动名称参数为空,这意味着该值尚未传递给控制器​​。

This is the code from the view: 这是视图中的代码:

         @foreach (var item in Model.Sports)
    {
        <p>
            @*@Html.ActionLink(@item, "Index", "Home")*@
            @Html.ActionLink(@item, "Index", "Home")

        </p> 
    }


</div>
<div class="col-md-4">
@foreach (var Coupon in Model.CurrentCoupons())
{
    <p>
        Coupon: @Coupon.CouponName <br />
        Event Count: @Coupon.EventsCollection.Count
        <br />
        Event:
        @foreach (var Event in Coupon.EventsCollection)
        {
            @Event.Name;<br /><br />
        }

        @foreach (var Market in Coupon.MarketList)
        {
            @Html.ActionLink(@Market.Name, "Index", "Home")<br />
        }
    </p>

    <table>    
        @foreach (var Selection in Coupon.SelectionList)
        {
            <tr>
                <td width="400">@Selection.Name</td>
                <td>@Selection.PriceFixed</td>
            </tr>
        }        
    </table>
}

Controller: 控制器:

public class HomeController : Controller
{
    public ActionResult Index(string sportName)
    {
        ViewBag.Title = sportName;
        return View(new TestDataHelper(sportName));
    }
}

@ Html.ActionLink方法的重载之一是路由值的对象,因此您也可以在执行以下操作时发送该值:

@Html.ActionLink("Soccer", "Index", "Home", new {sportName = @item}, null)

If, as by default, the routing is specified as follows: 如果,默认情况下,路由指定如下:

routes.MapRoute(
    name: "Default",
    url: "{controller}/{action}/{id}",
    defaults: new { controller = "Home", action = "Index", id = UrlParameter.Optional }
);

Then you need to name the parameter id : 然后你需要命名参数id

public ActionResult Index(string id)
{
    ViewBag.Title = id;
    return View(new TestDataHelper(id));
}

you can pass the parameter to the controller using an anonymous type like this: 您可以使用匿名类型将参数传递给控制器​​,如下所示:

@Html.ActionLink(@item, "Index", "Home", new { sportName = item })

check out the examples here: http://www.w3schools.com/aspnet/mvc_htmlhelpers.asp 看看这里的例子: http//www.w3schools.com/aspnet/mvc_htmlhelpers.asp

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM