Kavitha P.
Kavitha P.

Reputation: 155

How to pass a value as url in C#

I had specified like,

@foreach (int ans in Model.UnAnsweredList)
{
    <a href="/Dashboard/GoToAnswer?@ans/">@ans</a>
}

and its get method given as,

 public ActionResult GoToAnswer(int? number)

Even though the ans is int type, the value does not pass to the method. kindly tell me what should i do.

Upvotes: 2

Views: 401

Answers (3)

Ronald Rozema
Ronald Rozema

Reputation: 246

Try using HTML helpers.

@HTML.ActionLink(ans, "GoToAnswer", "ControllerName", new { number = ans })

Upvotes: -1

CodeCaster
CodeCaster

Reputation: 151588

If number is not in your routing, you should name the parameter:

<a href="/Dashboard/GoToAnswer?number=@ans/">@ans</a>

If it were in your routing, you wouldn't use the query string:

<a href="/Dashboard/GoToAnswer/@ans/">@ans</a>

Upvotes: 3

Vsevolod Goloviznin
Vsevolod Goloviznin

Reputation: 12324

When you use query string you need to specify the name of the parameter like name=value (as it's a key-value dictionary, so you cannot omit the parameter's name).

You need to change you link to this:

@foreach (int ans in Model.UnAnsweredList)
{
    <a href="/Dashboard/GoToAnswer?number=@ans">@ans</a>
}

But in fact, you should better use an Html.ActionLink method as your custom routes will be applied:

@foreach (int ans in Model.UnAnsweredList)
{
    @Html.ActionLink(ans, "GotToAnswer", "DashBoard", new {number=ans})
}

Upvotes: 9

Related Questions