将动态值从 html table 行传递到 javascript url.action

Pass dynamic value from html table row to javascript url.action

我想将选定的单元格值从 @Html.DisplayFor(model => item.year) 传递到我在 javascript 中创建的 Url.Action

我的控制器有两个参数,一个是静态名称,另一个是从所选行动态获取的年份。

table 代码:

<table id="name" border=1 width="50%">
    <tr>
        <th>Name</th>
        <th>Year</th>
    </tr>
    @foreach (var item in Model)
    {
        <tr>
            <td>
                <button id="see">@Html.DisplayFor(model => item.year)</button>
            </td>
        </tr>
    }
</table>

javascript 的代码:

<script type="text/javascript">
    var urls = {
       view: '@Html.Raw(@Url.Action("(actionName)", "(controller)", new { name = "Mary", year = (this is what idk)}))'
    };

    $document.ready(function()
    {
        $('#see').click(function () {
            $('#dialog').load(urls.view, function () {    
            });
        });
    });
</script>

控制器方法:

public ActionResult actionName(string name, string year)
{
    var query = new aquery();
    var response = query.Fetch(name, year);
    return View(response);
}

调用具有

的弹出表单
<form id="", action="@html.raw(@url.action(same thing here as my previous main page. what do i put for the year here now?))">

您不需要在@Url.Action 之前添加@Html.Raw,因为正如您在Documentation 中看到的那样,@Url.Action returns字符串

var urls = { view: '@Url.Action("actionName", 
                                "controllerName", 
                                 new {name = "mary", year = ?})' }

您的 html 无效,因为您向 foreach 循环中的按钮添加了重复的 id="see" 属性。首先将其更改为使用 class 名称,然后添加 type="button" 因为默认值为 "submit"

<button type="button" class="see">@Html.DisplayFor(model => item.year)</button>

脚本应该是

<script type="text/javascript">
  $document.ready(function()
  {
    var dialog = $('#dialog'); // cache elements you may repeatedly use
    var url = '@Url.Action("actionName")'; // add the controller name if its in a different controller
    $('.see').click(function () { // change selector to use the class name
      dialog.load(url, { name: 'Mary', year: $(this).text() });
    });
  }
</script>

旁注:您的方法参数应该是 int year,而不是 string year,您的方法应该是 return a PartialView(response),而不是 View(response)