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

时间:2015-11-16 02:53:33

标签: jquery asp.net-mvc url.action

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

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

表格代码:

<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?))">

2 个答案:

答案 0 :(得分:0)

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

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

答案 1 :(得分:0)

由于您添加到id="see"循环中的按钮的重复foreach属性,您的html无效。首先将其更改为使用类名,然后添加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,您的方法应该返回PartialView(response),而不是View(response)