表单提交后,将字典从视图传递到控制器

时间:2012-10-05 12:02:22

标签: asp.net-mvc-3 razor routevalues

Razor观点:

@using (Html.BeginForm("Move", "Details", new { dict= dictionary}, FormMethod.Post)) {
    //table with info and submit button
    //dictionary => is a dictionary of type <Sales_Order_Collected, string>
}

控制器操作:

[HttpPost]
public string Move(Dictionary<Sales_Order_Collected, string> dict) {
    return "";
}

有没有办法将模型字典传递给控制器​​?因为我的参数始终为null。

2 个答案:

答案 0 :(得分:1)

您无法通过路线值传递字典。你可以这样做:

@using (Html.BeginForm("Move", "Details", null, FormMethod.Post)) {
    <input type="text" name="[0].Key" value="first key"/>
    <input type="text" name="[0].Value" value="first value"/>

    <input type="text" name="[1].Key" value="second key"/>
    <input type="text" name="[1].Value" value="second value"/>
}

这将发布词典。复杂对象的想法是相同的

答案 1 :(得分:0)

这是我的任何字典的HTML帮助程序:

public static IHtmlString DictionaryFor<TModel, TKey, TValue>(this HtmlHelper<TModel> htmlHelper,
    Expression<Func<TModel, IDictionary<TKey, TValue>>> expression)
{
    ModelMetadata metaData = ModelMetadata.FromLambdaExpression(expression, htmlHelper.ViewData);

    IDictionary<TKey, TValue> dictionary = (IDictionary<TKey, TValue>)metaData.Model;

    StringBuilder resultSB = new StringBuilder();

    int i = 0;

    foreach (KeyValuePair<TKey, TValue> kvp in dictionary)
    {
        MvcHtmlString hiddenKey = htmlHelper.Hidden($"{metaData.PropertyName}[{i}].Key", kvp.Key.ToString());
        MvcHtmlString hiddenValue = htmlHelper.Hidden($"{metaData.PropertyName}[{i}].Value", kvp.Value.ToString());

        resultSB.Append(hiddenKey.ToHtmlString());
        resultSB.Append(hiddenValue.ToHtmlString());

        i++;
    }

    return MvcHtmlString.Create(resultSB.ToString());
}

在这样的视图中调用它:

@Html.DictionaryFor(model => model.AnyDictionary)