【问题标题】:What's the best way of getting Id from Url with asp.net mvc使用 asp.net mvc 从 Url 获取 ID 的最佳方法是什么
【发布时间】:2013-04-06 06:19:09
【问题描述】:

我是 Jquery 和 Asp.Net MVC 的新手。 我正在尝试传递一个 ID 参数

从页面上的 ActionLink 到 jQuery 函数。 然后将此 Id 传递给控制器​​,该控制器返回在模式对话框中呈现的结果集。

从 Jquery 函数中的 ActionLink 捕获 Id 参数的最佳方法是什么? 请注意,有几个分配了不同 ID 的操作链接。

这是我下面的操作链接:

<%=Html.ActionLink("View", "GetDetailsById", new { id = x.ProductId }, new { @class = "view",@productId= x.ProductId })%>

下面是我的 jquery 函数。

       $(function () {
             var _id;


             $(".view").click(function () {
                 // Get the ID value of this button.

                 _id = $(this).attr('productId');                    

                 // Initialize the dialog and call the next function
                 // to get the data.                  
                 $("#dialog-message").dialog('open');

                return false;
             });

请注意,我通过向 actionlink -@productId 添加自定义属性来实现此功能。然后我像这样使用 jquery 获取值:

$(".view").click(function () { // Get the ID value of this button.

                 _id = $(this).attr('productId');               

这个 Id 被传递给一个 jquery 函数,该函数调用控制器中的一个方法。

这是获取 ID 的好方法,还是有更简洁的方法?

问候

小乔

【问题讨论】:

  • 很好奇,但看起来您正在创建一个操作链接,但实际上并未使用该链接本身。而是单击返回 false 并执行其他操作。我说的对吗?
  • 我正在用 css 类和一个 Id 装饰动作链接。我没有显示所有代码,但我打开了一个模式对话框。

标签: jquery asp.net-mvc


【解决方案1】:

您可以通过在 html 属性参数中指定 id 来将 productId 分配给生成的 html 元素的 Id:

new { @class = "view", id = x.ProductId }

然后,您可以使用相同的方式获取生成的&lt;a&gt; 标签的id,即使用$(this).attr("id"),而不是使用productId 属性。

我建议不要使用 productId,因为 id 是有效的 HTML。

因此,您的代码最终将如下所示:

<%=Html.ActionLink("View", "GetDetailsById", new { id = x.ProductId }, new { @class = "view", id = x.ProductId })%>

这将生成一个&lt;a&gt;,ID 为productId。然后你的 jQuery 看起来像这样:

       $(function () {
         var _id;


         $(".view").click(function () {
             // Get the ID value of this button.

             _id = $(this).attr('id');                    

             // Initialize the dialog and call the next function
             // to get the data.                  
             $("#dialog-message").dialog('open');

            return false;
         });

【讨论】:

  • ..我使用了 $(this).attr('id') 但它返回 undefined ,有什么想法吗?我只想在 jquery click 事件的上述 actionlink 中获取 id 值
【解决方案2】:

我会将 id 传递给视图模型,然后手动将值插入到 javascript 变量中

<script type="text/javascript">
     var id = '<% ViewData["theid"] %>';
</script>

这与 stackoverflow 在他们的代码中使用的技术相同。继续看他们的html,你会看到。

【讨论】:

  • 这是一种有用的技术并且会起作用。我不接受它的唯一原因是因为我有一个 List 数据集合,该集合显示在页面上的表格中。所以我不能在页面上显示之前将单个 ID 分配给 。
猜你喜欢
  • 2010-12-02
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2010-09-13
相关资源
最近更新 更多