简体   繁体   中英

getting anchor tag href on click from Action Method

I have a grid which includes below hyperlink row,currently for all rows we have same hyperlink and only ID is changing and it is working fine.

<a href=" + @ViewBag.Url+ ID + " target='_blank'>Test</a>

Now for every row, we have different link url which i would get from action method when I pass ID. I want to call MVC Action Method to get hyperlink url and then open it in another tab.How can I accomplish this? I tried this one but it is not opening hyperlink?

<div class="row">
    <div class="col-md-4">
        <a href="@Url.Action("GetUrl", "Home",new { id = 1 })">Click Here</a>;
    </div>
</div>

 public string GetPDFUrl(string id)
        {

            return "test.com" + id;
        }

There are several ways to solve your problem. one of them is using child actions. Put your generating URL part into a partial view to put your logic in your action method. So, create a child action method that can only be called in your views.

    [ChildActionOnly]
    public ActionResult GenerateUrlPartial(int id)
    {
        var generatedUrl = "";//your url business is here
        var model = new UrlInfo { Url = generatedUrl };
        return PartialView(model);
    }

Then, create GenerateUrlPartial.cshtml partial view :

@model UrlInfo
@{
   Layout = null;
   ViewBag.Title = "GenerateUrlPartial";
 }

<div class="row">
    <div class="col-md-4">
        <a href="@Model.Url">Click Here</a>;
    </div>
</div>

And in your loop, call the action method like this :

@for (int i = 0; i < 10; i++)
{
     Html.RenderAction("GenerateUrlPartial", new { id = i });
}

Hope this helps.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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