4

I am trying to pass through a value from my view to my controller based on what I click on, using 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));
    }
}

3 Answers 3

3

One of the overloads for the @Html.ActionLink method takes an object for routevalues, so you could also send that value in doing something like:

@Html.ActionLink("Soccer", "Index", "Home", new {sportName = @item}, null)
Sign up to request clarification or add additional context in comments.

Comments

2

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

1 Comment

Sorry @qbik, I was typing mine in and didn't see that you posted that. I upvoted yours
2

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:

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.