2016-09-07 44 views
-1

是否有可能將formcollection轉換爲已知的「模型」?如何將formcollection轉換爲mvc中的模型

[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='[email protected]' 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-屬性是引導酥料餅。

+1

請勿使用表單集合。使用'公共ActionResult(學生模型)',以便其正確綁定,並利用MVC的所有其他功能,包括驗證 –

+0

請發佈您的視圖代碼和模型代碼。另外,你爲什麼要這樣做?是因爲你不知道模型綁定? – ekad

+0

@ekad再次檢查我的代碼'data-content' – sridharnetha

回答

1

你可以試試這個方法

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

在MVC的另一種方法是使用TryUpdateModel

示例: TryUpdateModel或UpdateModel將從已發佈的表單集合中讀取並嘗試將其映射到您的類型。我發現這比手動手動映射字段更優雅。

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

    UpdateModel<Student>(model); 

    return View(model); 
} 
相關問題