从HTML编码输出中防止Ajax.BeginForm

时间:2011-06-01 00:12:50

标签: html asp.net-mvc razor

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

输出以下标记:

<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只能采用函数名(而不是状态),那么我该如何实现呢?

3 个答案:

答案 0 :(得分:2)

就个人而言,我会使用标准Html.BeginForm帮助程序,其中包含HTML5 data-*属性,我将自己进行AJAX化:

@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.*助手相比,我更喜欢这种技术,因为它给了我可能需要的所有控制权。另一个优点是我们可以清楚地分离脚本和标记,使代码变得整洁。

答案 1 :(得分:0)

别。

HTML编码是正确的行为,属性值(从Javascript代码看)不会被编码。

答案 2 :(得分:0)

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

创建一个帮助函数,执行您想要对提交执行的脚本。

相关问题