我的视图中有一个超链接,其文本取决于后面的代码:
<a href="http://somelink"> @Html.DisplayFor(m => m.Link) </a>
在我的模型中:
[Display(Name = "Link")]
public string Link { get; set; }
在我的控制器中:
public ActionResult Index(string id)
{
Models.Home DLink = new Models.Home();
DLink.Link = id;
return View(DLink);
}
如预期的那样,我可以更改超链接描述http://localhost:61227/Home/Index/hyperlinkdescription
现在我的问题是:我无法使用按钮onclick
更改超级链接描述,如下所示:
<button class="but-lay" id="but-id" type="submit" onclick="location.href='@Url.Action("Index", "Home", new {id = "something" })'" >Button</button>
此按钮位于Hyperlink和控制器的同一view
中。
更新:如果我为该按钮使用type="button"
,则问题将会解决,但用户可以使用Enter键而不是按按钮。
答案 0 :(得分:0)
您的控制器
//namespace Testy20161006.Controllers
public class ReloadPageViewModel
{
[Display(Name = "Link")]
public string Link { get; set; }
}
public class HomeController : Controller
{
public ActionResult ToIndex()
{
//put a breakpoint here to go to this action,
//after url change
ReloadPageViewModel DLink = new ReloadPageViewModel();
DLink.Link = "http://somelink";
return View(DLink);
}
public ActionResult Tut116()
{
ViewBag.MyURL = "http://www.Google.com";
ReloadPageViewModel DLink = new ReloadPageViewModel();
//don't show you this property, I concentrate on your main problem,
//which is, how a button click, can change href
DLink.Link = "6";
return View(DLink);
}
您的视图
@{
Layout = null;
}
@model Testy20161006.Controllers.ReloadPageViewModel
<!DOCTYPE html>
<html>
<head>
<meta name="viewport" content="width=device-width" />
<title>Tut116</title>
<script src="~/Scripts/jquery-1.12.4.min.js"></script>
<script type="text/javascript">
$(function () {
$("#but-id").click(function () {
$("a").text("to home index")
$("a").attr("href", "/Home/ToIndex/")
})
})
</script>
</head>
<body>
<div>
<a id="theLink" href="@Html.Raw(Html.AttributeEncode(ViewBag.MyURL))"
title="@Html.Raw(Html.AttributeEncode(ViewBag.MyURL))">
google
</a>
<button class="but-lay" id="but-id" type="button">
Change HREF of link Button
</button>
</div>
</body>
</html>
答案 1 :(得分:0)
In Your Layout.cshtml page SET the ROOT
<script>
var ROOT = '@Url.Content("~/")';
</script>
Now Give a id to <a id="hreflink"></a>
. On button click write the below script
$('#hreflink').each(function () {
var oldUrl = $(this).attr("href"); // Get current url
var url = ROOT + "new link?id1=" + value1+ '&id2=' + value2;
$(this).attr("href", url); // Set herf value
});
you are good to go .