【问题标题】:how to convert formcollection to model in mvc如何将formcollection转换为mvc中的模型
【发布时间】:2017-01-14 20:10:38
【问题描述】:

是否可以将formcollection 转换为已知的“模型”?

[HttpPost]
    public ActionResult Settings(FormCollection fc)
    {
    var model=(Student)fc; // Error: Can't convert type 'FormCollection' to 'Student'
    }

注意:由于某些原因,我不能使用 ViewModel。

这是我的代码查看:Settings.cshtml

@model MediaLibrarySetting
@{
ViewBag.Title = "Library Settings";
var extensions = (IQueryable<MediaLibrarySetting>)(ViewBag.Data);    
}
@helper EntriForm(MediaLibrarySetting cmodel)
{   

<form action='@Url.Action("Settings", "MediaLibrary")' id='MLS-@cmodel.MediaLibrarySettingID' method='post' style='min-width:170px' class="smart-form">
    @Html.HiddenFor(model => cmodel.MediaLibrarySettingID)
    <div class='input'>
        <label>
       New File Extension:@Html.TextBoxFor(model => cmodel.Extention, new { @class = "form-control style-0" })
        </label>
        <small>@Html.ValidationMessageFor(model => cmodel.Extention)</small>
    </div>
    <div>
        <label class='checkbox'>
            @Html.CheckBoxFor(model => cmodel.AllowUpload, new { @class = "style-0" })<i></i>&nbsp;
            <span>Allow Upload.</span></label>
    </div>
    <div class='form-actions'>
        <div class='row'>
            <div class='col col-md-12'>
                <button class='btn btn-primary btn-sm' type='submit'>SUBMIT</button>
            </div>
        </div>
    </div>
</form>
}
<tbody>
@foreach (var item in extensions)
 {
  if (item != null)
   {                                    
    <tr>
     <td>
      <label class="checkbox">
       <input type="checkbox"  value="@item.MediaLibrarySettingID"/><i></i>
        </label>
          </td>
           <td>
             <a href="javascript:void(0);" rel="popover" class="editable-click"
            data-placement="right"
            data-original-title="<i class='fa fa-fw fa-pencil'></i> File Extension"
            data-content="@EntriForm(item).ToString().Replace("\"", "'")" 
            data-html="true">@item.Extention</a></td>
                    </tr>
                    }
                }
                </tbody>

控制器:

[HttpPost]
public ActionResult Settings(FormCollection fc)//MediaLibrarySetting cmodel - Works fine for cmodel
{
        var model =(MediaLibrarySetting)(fc);// Error: Can't convert type 'FormCollection' to 'MediaLibrarySetting'
}

data-contentdata- 属性是引导弹出窗口。

【问题讨论】:

  • 不要使用表单集合。使用 public ActionResult (Student model) 使其正确绑定,您可以利用 MVC 的所有其他功能,包括验证
  • 请发布您的视图代码和型号代码。另外,你为什么要这样做?是不是因为你不了解模型绑定?
  • @ekad 再次检查我的代码data-content
  • @ekad yes MediaLibrarySetting cmodel 因为参数工作正常并且问题已解决,但我期待回答我的问题 是否可以将 FormCollection 转换为模型?
  • @sridharnetha,不,不可能。它们不是同一类型。这就像问如何将苹果扔到香蕉上。

标签: asp.net-mvc asp.net-mvc-4 c#-4.0 formcollection


【解决方案1】:

MVC 中的另一种方法是使用TryUpdateModel

示例: TryUpdateModel 或 UpdateModel 将从发布的表单集合中读取并尝试将其映射到您的类型。我发现这比手动手动映射字段更优雅。

[HttpPost]
public ActionResult Settings()
{
    var model = new Student();

    UpdateModel<Student>(model);

    return View(model);
}

【讨论】:

    【解决方案2】:

    好问题! 在制作通用基础控制器、模型独立的过程中也有同样的想法。感谢很多人,最后一个是@GANI,它已经完成了。

    Type ViewModelType 在子类控制器中设置为您想要的任何内容。

    public ActionResult EatEverything(FormCollection form)
            {    
                var model = Activator.CreateInstance(ViewModelType);
                Type modelType = model.GetType();
    
            foreach (PropertyInfo propertyInfo in modelType.GetProperties())
            {
                var mykey = propertyInfo.Name;
                if (propertyInfo.CanRead && form.AllKeys.Contains(mykey))
                {
                    try
                    {
                        var value = form[mykey];
                        propertyInfo.SetValue(model, value);
                    }
                    catch 
                    {
                        continue;
                    }
                }
            }
    

    现在您从未知表单收到的所有内容都在您的真实模型中,您可以从这篇帖子 https://stackoverflow.com/a/22051586/7149454 进行验证

    【讨论】:

      【解决方案3】:

      你可以试试这个方法

         public ActionResult Settings(FormCollection formValues)
         {
           var student= new Student();
           student.Name = formValues["Name"];
           student.Surname = formValues["Surname"];
           student.CellNumber = formValues["CellNumber"];
          return RedirectToAction("Index");
         }
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2012-06-23
        • 2015-03-29
        • 2011-02-15
        • 2012-10-05
        • 1970-01-01
        • 2011-03-22
        • 2020-08-25
        相关资源
        最近更新 更多