Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

MVC 4 - Razor - Pass a variable into a href url

How can I pass a variable into a url?

What I try is this but this is not working. The url only shows this:

http://myurltest.com and not the full path

@if(check1 != "d")
{    
    <li>
        <div class="a"></div>
    </li>
    <li>
        <div class="b"></div>
    </li>
    <li>
        <a href="http://myurltest.com/" + @check1 + "/go/5/true">
        <div class="c"></div>
        </a>
    </li>
}
like image 311
user2232273 Avatar asked Feb 17 '14 11:02

user2232273


5 Answers

Using String Interpolation in C# 6

<a href="@($"http://myurltest.com/{check1}/go/5/true")" >

Wiki

In computer programming, string interpolation or variable interpolation (also variable substitution or variable expansion) is the process of evaluating a string literal containing one or more placeholders, yielding a result in which the placeholders are replaced with their corresponding values. It is a form of simple template processing.2 or, in formal terms, a form of Quasi-quotation (or logic substitution interpretation). String interpolation allows for easier and more intuitive string formatting and content-specification compared with string concatenation.

MSDN

like image 20
Sandip Bantawa Avatar answered Nov 04 '22 11:11

Sandip Bantawa


Like this:

<a href='@string.Format("http://myurltest.com/{0}/go/5/true", check1)'>

The point is to insert the whole URL into the markup, rather than combining markup and code parts.

like image 178
Andrei Avatar answered Nov 04 '22 11:11

Andrei


If it points to an action of your website/app then you should use

@Url.Action(your parameters)

inside your href attribute.

Notice you can also generate the full link with

@Html.ActionLink(your parameters)

Those are overloaded methods, Intellisense or google will describe all possible alternatives.

Usually, for links to actions of the same website, these methods are better than manipulating the url string like the proposed "http://myurltest.com/@check1/go/5/true" because can be used on local machine (where base URL is localhost:someport) and better than "@check1/go/5/true" (relative path) because avoids deployment-time URL mismatches.

On the other side, if the link points to external resource then something like the proposed <a href="http://myurltest.com/@check1/go/5/true"> is fine.

Have a nice day,

Alberto

like image 9
Alberto Avatar answered Nov 04 '22 10:11

Alberto


Try this it is working

  <a href="http://myurltest.com/@check1/go/5/true">
like image 6
Nilesh Gajare Avatar answered Nov 04 '22 10:11

Nilesh Gajare


try this:

<a href="@Url.Content("~/id?" + check1)">click here</a>
like image 6
Bhupendra Shukla Avatar answered Nov 04 '22 10:11

Bhupendra Shukla