MVC 5 AJax.Beginform Routevalues生成错误

时间:2016-10-13 09:05:06

标签: ajax asp.net-mvc routes ajax.beginform

我正在尝试发布当前的查询字符串。所以我创建了以下扩展方法:

public static RouteValueDictionary ToRouteValues(this NameValueCollection col, Object obj = null)
        {
            var values = obj != null ? new RouteValueDictionary(obj) : new RouteValueDictionary();
            if (col == null) return values;
            foreach (string key in col)
            {
                //values passed in object are already in collection
                if (!values.ContainsKey(key)) values[key] = col[key];
            }
            return values;
        }

在我看来,我正在使用如下的溃败值:

 using (Ajax.BeginForm(actionName: "Post", routeValues:Request.QueryString.ToRouteValues(), controllerName: "Request", ajaxOptions: new AjaxOptions { HttpMethod = "Post", OnSuccess = "SuccessCallBack", UpdateTargetId = "successDiv", InsertionMode = InsertionMode.InsertAfter }, htmlAttributes: new { @data_toggle = "validator" }))
        {
        }

但奇怪的是,当生成html标记时,表单标记操作没有实际的查询字符串值,而是具有对象元数据的字符串版本。

<form action="/Request/Post?Count=5&amp;Keys=System.Collections.Generic.Dictionary%602%2BKeyCollection%5BSystem.String%2CSystem.Object%5D&amp;Values=System.Collections.Generic.Dictionary%602%2BValueCollection%5BSystem.String%2CSystem.Object%5D" data-ajax="true" data-ajax-method="Post" data-ajax-mode="after" data-ajax-success="SuccessCallBack" data-ajax-update="#successDiv" data-toggle="validator" id="form0" method="post" novalidate="true">

2 个答案:

答案 0 :(得分:2)

这对我有用:

@using (Ajax.BeginForm(
    actionName: "AddOns",
    controllerName: "Basket",
    routeValues: Request.QueryString.ToRouteValues(),
    ajaxOptions: new AjaxOptions { HttpMethod = "Post", OnSuccess = "SuccessCallBack", UpdateTargetId = "successDiv", InsertionMode = InsertionMode.InsertAfter },
    htmlAttributes: new Dictionary<string, object> { { "class", "mainForm" } }))
{
    @:Blah
}

输出:

<form action="/Basket/AddOns?test=test" class="mainForm" data-ajax="true" data-ajax-method="Post" data-ajax-mode="after" data-ajax-success="SuccessCallBack" data-ajax-update="#successDiv" id="form0" method="post">
    Blah
</form>

请注意最后一个参数Dictionary<string, object>

将此帖子用作来源:MVC3 Html.BeginForm - passing arguments as RouteValueDictionary fails

答案 1 :(得分:1)

问题在于您使用命名参数并且Ajax.BeginForm()的重载同时接受object routeValuesRouteValueDictionary routeValues

在您的情况下,使用object routeValues并为RouteValueDictionaryCountKeys等每个属性生成路线值。我假设那是因为首先定义了object routeValues的重载(但是还没有找到记录行为的东西)

您可以通过省略名称并使用

来解决此问题
@using (Ajax.BeginForm("Post", "Request", Request.QueryString.ToRouteValues(), new AjaxOptions { HttpMethod = "Post", OnSuccess = "SuccessCallBack", UpdateTargetId = "successDiv", InsertionMode = InsertionMode.InsertAfter }, new { @data_toggle = "validator" }))
{
}