在mvc3中将Id从javascript传递给Controller



如何将Id从javascript传递到ajax上mvc3中的Controller操作提交

我的脚本

   <script type="text/javascript">
    $(document).ready(function () {
        $("#tblclick td[id]").each(function (i, elem) {
            $(elem).click(function (e) {
                var ID = this.id;
                alert(ID);
               // var url = '@Url.Action("Listpage2", "Home")'; 
                var data = { Id: ID };
//                  $.post(url,data, function (result) {
//                 }); 
                e.preventDefault();
                $('form#myAjaxForm').submit();
            });
                       });
    });
</script>

如何使用$('form#myAjaxForm').submit()传递Id;至控制器而不是

$.post(url,data, function (result) {
    //                 }); 

我的视图

 @using (Ajax.BeginForm("Listpage2", "", new AjaxOptions
            {
                UpdateTargetId = "showpage"
            }, new { @id = "myAjaxForm" }))
            {
                <table id="tblclick">
                    @for (int i = 0; i < Model.names.Count; i++)
                    {
                        <tr>
                            <td id='@Model.names[i].Id'>
                                @Html.LabelFor(model => model.names[i].Name, Model.names[i].Name, new { @id = Model.names[i].Id })
                              <br />
                            </td>
                        </tr>
                    }
                </table>
            }
        </td>
        <td id="showpage">
        </td>

我会避免使用Ajax Beginform辅助方法,而是像这个一样使用一些纯手写和Cleanjavascript

<table id="tblclick">
  @foreach(var name in Model.names)
  {
    <tr>
     <td id="@name.Id">
           @Html.ActionLink(name.Name,"listpage","yourControllerName", 
                         new { @id = name.Id },new { @class="ajaxShow"})         
     </td>
    </tr>
   }
</table>
<script>
 $(function(){
    $(".ajaxShow")click(function(e){
       e.preventDefault();
       $("#showpage").load($(this).attr("href")); 
    });
 });
</script>

这将为每个循环生成锚标记的标记,如下所示。

<a href="/yourControllerName/listpage/12" class="ajaxShow" >John</a>
<a href="/yourControllerName/listpage/35" class="ajaxShow" >Mark</a>

当用户点击链接时,它使用jQuery load函数将响应从thae listpage操作方法加载到id为showPage的div。

假设您的listpage操作方法接受一个id参数并返回一些

我不确定$.post,但我知道window.location对我来说很好。用这个代替,希望你有好的结果:)

window.location = "@(Url.Action("Listpage2", "Home"))" + "Id=" + ID;

替换$('form#myAjaxForm').submit();有了这些代码,您的jscript就不会出现任何明显的错误。

只需使用带有html属性ID的文本框帮助程序。

@Html.TextBox("ID")

你也可以这样做:

 var form = $('form#myAjaxForm');
 $.ajax({
       type: "post",
       async: false,
       url: form.attr("action"),
       data: form.serialize(),
       success: function (data) {
          // do something if successful
          }
 });

相关内容

最新更新