【问题标题】:Pass dictionary from view to controller after form submit表单提交后将字典从视图传递到控制器
【发布时间】:2012-10-05 12:02:22
【问题描述】:

剃刀视图:

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

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

【问题讨论】:

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


    【解决方案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"/>
    }
    

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

    【讨论】:

      【解决方案2】:

      这是我的任何字典的 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)
      

      【讨论】:

        猜你喜欢
        • 2014-05-29
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多