ASP.NET MVC:在Ajax Update中将Javascript值传递给Url.Action

Ian*_*ink 1 ajax asp.net-mvc asp.net-mvc-4

使用MVC 4:

我正在通过ajax更新div.对Url.Action的调用需要传递来自html DOM的值,在本例中为$('#ClientID').val().我知道下面的内容是非法的,但它表明了我的意图:

[script type="text/javascript"]
function UpdateTheDiv() {
    $.get('@Url.Action("MyAction", "MyController", 
        new {  
               parent = Model, 
               some_value_from_the_DOM=$('#SomeID').val() *** HERE IS THE PROBLEM ***
             })', 

        function (data) {
           $('#detailsDiv').replaceWith(data);
    }); 
}
Run Code Online (Sandbox Code Playgroud)

可以这样做吗?

Tom*_*ski 5

您应该使用Url.Action不带参数并在JavaScript中传递参数.服务器端处理无法访问客户端DOM.

    $.ajax({
        url: "@Url.Action("MyAction", "MyController")",
        data: { 
                parent: @Html.Raw(Json.Encode(Model)),
                some_value_from_the_DOM: $('#SomeID').val()
        },
        success: function (result) {
            $("#detailsDiv").html(result); // update your div here
        },
        cache: false
    });
Run Code Online (Sandbox Code Playgroud)