如何在MVC剃刀视图中将值从jQuery脚本传递到ActionLink
问题描述:
大家好,我希望快速的问题。如何在MVC剃刀视图中将值从jQuery脚本传递到ActionLink
我想从一个jQuery脚本的值传递到HTML.ActionLink细节动作控制器
它的工作就像我在下拉列表和jQuery的选择项,我得到该项目的ID后,我想得到该ID传递到ActionLink我怎么能实现它,或者我要改变我的代码。
<script>
$(function() {
$('#reductions').change(function() {
var Id = $('#reductions').val();
});
});
</script>
<div class="form-horizontal">
<div class="form-group">
<div class="col-md-10">
@Html.DropDownList("reductions", new SelectList(dbContext.Reductions,"ReductionId", "Name")
</div>
</div>
</div>
@Html.ActionLink("Details", "Details", "Reductions", new {id = ????WHAT PUT HERE?????}, new {})
请告诉我,我应该改变脚本区域还是在Action Link中,我可以让我工作。 我已经学习了很多例子,但似乎没有人为我工作
答
而不是使用ActionLink方法创建一个正常的HTML链接,并用jQuery覆盖href属性。
<script>
$(function() {
var link = '@Url.Action("Details", "Details", "Reductions", new { id = "_myid_" })';
$('#reductions').change(function() {
var id = $('#reductions').val();
$('#myLink').attr('href', link.replace('_myid_', id);
});
});
</script>
... Your other html
<a id="myLink" href="">Details</a>
答
而不是使用普通的HTML表单的使用:
@using(HTML.BeginForm("Details","Reductions"))
{
//Your current HTML
}
你应该也可以用@ HTML.DropDownListFor()辅助这样的:
@Html.DropDownListFor("reductions", new SelectList(DBContext.Reductions, "ReductionId", "Name"), new { @class = "anyCSSClass" })
替换当前的@ HTML.DropDownList()这个助手。
才能完成,你必须在表格数据提交到这样的服务器:
button type="submit" class="CSSClass" id="generatedContent"> Generate </button>
继承人的最终代码:
@using(HTML.BeginForm("Details","Reductions"))
{
@Html.DropDownListFor("reductions", new SelectList(DBContext.Reductions, "ReductionId", "Name"), new { @class = "anyCSSClass" })
button type="submit" class="CSSClass" id="generatedContent"> Generate </button>
}
你可以做到这一点使用JQuery/AJAX,但它多了很多因为它违背了MVC的基本概念,并且保持服务器端逻辑与客户端逻辑分离,所以它比它的价值更令人困惑。
P.S.如果我混淆了控制器/操作方法的名称,请检查帮助者here的超载方法。
请发送渲染的动作链接html。 – tymeJV 2014-11-21 13:58:55