Ajax.BeginForm(),OnSuccess - 获取事件目标

6

我无法获取由 Ajax.BeginForm() 触发的 OnSuccess() 方法的元素目标。以下是代码片段:

@using (Ajax.BeginForm("InsertModel", "Home", new AjaxOptions
{
    HttpMethod = "POST",
    OnSuccess = "doWork(this,'SomeCustomText')"
}))
{
    <div id="container">
       <--Some HTML--!>
      <input type="submit" value="OK"/>
    </div>
}

<script>
function doWork(e,customText)
{
   alert(customText);  //It shows 'SomeCustomText', so its good.

   alert(e);  //[Object] object
   alert(e.prop("tagName"));  //Object #<Object> has no method 'prop' 
   alert(e.attr("tagName"));  //Object #<Object> has no method 'attr' 
   alert(jQuery(e).html());  //undefined
   alert(jQuery(e).prop("tagName"));  //undefined
   alert(e.target);  //undefined
   alert(jQuery(e).target);  //undefined
 }
<script/>

问题:

如何获取目标?谢谢。

更新 1

jQuery 版本应该像这样:

jQuery.ajax({
    url:"/Home/InsertModel",
    data:"some post data",
    type:"POST",
    success:function(data){ 
          doWork(this,data); // so i really do not care about data! I just need jQuery(this)
    }
  })

生成的HTML是什么? - Trevor Elliott
我不关心返回的 data。这里有一个例子:jQuery.ajax(){url:"/Home/Insert",type:"POST",success:function(data){ alert(data); // 所以我不关心 data!我只需要 jQuery(this); 其中 this - 我想应该是 form()}} - Cristian E.
你的问题有点不清楚。你所说的“哪个元素触发了OnSuccess()”是什么意思? - keeehlan
试着思考一下,在 OnSuccess = "doWork(this,'SomeCustomText')" 中,this 是谁。 - Cristian E.
1个回答

5
如果您想访问表单元素,有许多选项。如果页面上只有一个表单,您可以使用$("form")命令,jQuery将返回表单元素。
另一个选项是更改以表单ID作为参数的Ajax.BeginForm构造函数,如下所示:
@using (Ajax.BeginForm("InsertModel", "Home",null, new AjaxOptions
{
    HttpMethod = "POST",
    OnSuccess = "doWork('SomeCustomText')"
}, new {id = "myFormId"}))
{
    <div id="container">
       <--Some HTML--!>
      <input type="submit" value="OK"/>
    </div>
}

在 JavaScript 中,
<script>
function doWork(customText)
{
   alert(customText);  //It shows 'SomeCustomText', so its good.

   // find the form by id
   $("#myForm1");

   // find forms in the page
   $("form")


 }
<script/>

使用纯JQuery:

$.ajax({
    url:"/Home/InsertModel",
    data:"some post data",
    type:"POST",
    success:function(data){ 
       // find the form by id
       $("#myForm1");

       // find forms in the page
       $("form")        

       ...
    }
  });

你的“javascript”示例使用了jQuery,因此需要一个jQuery库。 - keeehlan
他已经在问题中使用了Jquery... Jquery与$符号相同。 - hjgraca
我知道这一点,但你说的是“在JavaScript中”,实际上是jQuery。 - keeehlan
1
谢谢您的回答,这是一个好观点,但它并不适合我的情况。因为我有10多个类似于这个的表单,或者说嵌套的表单,所以我有兴趣使用this来做一些通用的事情,以避免硬编码formId。MVC已经使用内置的Ajax.BeginForm()助手生成了一个formId。再次感谢。 - Cristian E.

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接