2

剃刀视图:

@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 "";
}

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

4

2 回答 2

4

您不能通过路由值传递字典。你可以这样做:

@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"/>
}

这将发布字典。复杂对象的想法是一样的

于 2012-10-05T12:16:50.703 回答
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)
于 2020-06-26T17:54:02.430 回答