2011-06-01 51 views
0
@using (Ajax.BeginForm("Create", "Comment", 
    new AjaxOptions 
    { 
     UpdateTargetId = "newComment", 
     OnSuccess = "function() { alert('finished " + ViewData.Model.Id + "'); }", 
    })) 
{ 
    ... 
} 

输出以下标记:防止Ajax.BeginForm从HTML编码输出

<form action="/Comment/Create" data-ajax="true" data-ajax-mode="replace" 
data-ajax-success="function() { alert(&#39;finished 34&#39;); }" 
data-ajax-update="#newComment34" id="form1" method="post"> 

正如你所看到的,它具有HTML编码我的JavaScript。我如何防止这种情况?

编辑:我在我的页面上有多个AJAX表单,所以onsuccess函数需要知道哪一个叫它。在我的代码中,你可以看到我试图将状态传递给这个函数。如果OnSuccess只能使用一个函数名(而不是状态),那我该如何实现呢?

回答

2

个人而言,我会用一个标准Html.BeginForm帮手与HTML5 data-*属性,我将AJAXify自己:

@using (Html.BeginForm(
    "Create", 
    "Comment", 
    FormMethod.Post, 
    new { data_id = Model.Id } 
)) 
{ 
    ... 
} 

,输出:

<form action="/Comment/Create" data-id="some id here" method="post"> 
    ... 
</form> 

,然后在一个单独的JavaScript文件我将认购.submit事件:

$(function() { 
    $('form').submit(function() { 
     $.ajax({ 
      url: this.action, 
      type: this.method, 
      data: $(this).serialize(), 
      dataId: $(this).data('id'), // <- pass the data-id HTML5 attribute 
      success: handleSuccess 
     }); 
     return false; 
    }); 
}); 

function handleSuccess(result) { 
    $('#newComment').html(result); 

    // fetch the data-id of the form that trigerred the AJAX request 
    var id = this.dataId; 

    // TODO: do something with this id 
} 

我喜欢这种技术,与Ajax.*佣工相比,因为它给了我可能需要的所有控制。另一个优点是我们清楚地区分了脚本和标记,使代码更加整洁。

+0

感谢您的解决方法。 – 2011-06-01 07:18:08

0

不要。

HTML编码是正确的行为,并且属性值(如从Javascript代码中看到的)将不会被编码。

0

我相信这是因为MVC将OnSuccess(和其他变量)解释为Javascript函数的名称,而不是一点Script。

做一个帮助函数,执行您想要对提交进行操作的脚本。

+0

那么我该如何将状态传递给这个函数呢?我的页面上有多个这样的ajax表单,而成功函数需要知道哪个表单调用了它。 – 2011-06-01 00:35:56