Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/ios/97.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
从HTML编码输出中防止Ajax.BeginForm_Html_Asp.net Mvc_Razor - Fatal编程技术网

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

从HTML编码输出中防止Ajax.BeginForm,html,asp.net-mvc,razor,Html,Asp.net Mvc,Razor,输出以下标记: @using (Ajax.BeginForm("Create", "Comment", new AjaxOptions { UpdateTargetId = "newComment", OnSuccess = "function() { alert('finished " + ViewData.Model.Id + "'); }", })) { ... } 如您所见,它对我的javascript进行了HTML

输出以下标记:

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

如您所见,它对我的javascript进行了HTML编码。我如何防止这种情况

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

不要


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

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


制作一个助手函数,执行您希望在提交时执行的脚本。

就我个人而言,我会使用标准的
Html。BeginForm
helper和HTML5
数据-*
属性,我将对自己进行调整:

<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">
哪些产出:

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

Ajax.*
helpers相比,我更喜欢这种技术,因为它提供了我可能需要的所有控制。另一个优点是,我们在脚本和标记之间获得了清晰的分离,从而使代码变得美观整洁。

那么,如何将状态传递给此函数?我的页面上有多个这样的ajax表单,success函数需要知道哪个表单调用了它。
<form action="/Comment/Create" data-id="some id here" method="post">
    ...
</form>
$(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
}