2011-10-20 170 views
1

我有一個視圖模型視圖模型

public class DeviceModelEntryViewModel 
{ 
    public int ID { get; set; } 

    [Required] 
    [MaxLength(255)] 
    public String Model { get; set; } 

    [MaxLength(255)] 
    public String Description { get; set; } 

    [Required] 
    [Display(Name = "Manufacturer")] 
    public int ManufacturerID { get; set; } 

    public SelectList ManufacturerList { get; set; } 
} 

DeviceModelController我的創建方法是這樣的:

[HttpPost] 
public ActionResult Create(DeviceModelEntryViewModel model) 
{ 
    if (ModelState.IsValid) 
    { 
     ... 
     return RedirectToAction("Edit", new { id }); 
    } 

    return View(model); 
} 

創建視圖如下:

@model ICMDB.ViewModels.DeviceModelEntryViewModel 

@{ ViewBag.Title = "ICMD - Create Device Model"; } 

<h2>Create Device Model</h2> 

<div class="form-div"> 
    @using (Html.BeginForm()) { 
     @Html.ValidationSummary(true) 

     <fieldset> 
      <div class="editor-label"> 
       @Html.LabelFor(model => model.Model) 
      </div> 
      <div class="editor-field"> 
       @Html.EditorFor(model => model.Model) 
       @Html.ValidationMessageFor(model => model.Model) 
      </div> 

      <div class="editor-label"> 
       @Html.LabelFor(model => model.Description) 
      </div> 
      <div class="editor-field"> 
       @Html.EditorFor(model => model.Description) 
       @Html.ValidationMessageFor(model => model.Description) 
      </div> 

      <div class="editor-label"> 
       @Html.LabelFor(model => model.ManufacturerID) 
      </div> 
      <div class="editor-field"> 
       @Html.DropDownListFor(model => model.ManufacturerID, 
             Model.ManufacturerList, "--None--") 
       @Html.ValidationMessageFor(model => model.ManufacturerID) 
      </div> 
     </fieldset> 

     <input type="submit" value="Save" class="form-button"/> 
    } 

    @using (Html.BeginForm("Index", "DeviceModel")) 
    { <input type="submit" value="Cancel" class="form-button"/> }  
</div> 

出於某種原因,無論何時該功能(或編輯功能具有類似的d被點擊,model爲空。我檢查了它,它甚至沒有打到DeviceModelEntryViewModel的零參數構造函數。我已經爲我的所有其他控制器和他們適當的視圖模型做了這些,他們都很好。我似乎無法看出與這個阻止它工作的區別。

任何想法?

+0

默認的model binder失敗。有很多原因可以發生。 – asawyer

+0

我該如何調試? – link664

+0

對不起,對於延遲響應,但基本上檢查ViewData.ModelState.IsValid,如果它通過ModelState鍵/值對集合錯誤查找,則有一個ErrorMessage/Exception類。我有一個擴展方法將所有綁定錯誤轉儲到調試控制檯。 – asawyer

回答

1

試着改變你的Model屬性的名稱是這樣的:

public String ModelName { get; set; }

不要忘記更新您的看法也是如此。我相信應該讓它正常工作,因爲Model這個詞似乎像一個保留字一樣起作用,並混淆了模型聯編程序。

編輯:下面是保留字在剃刀/ MVC的列表:Razor reseverd words

+0

就是這樣。謝謝@Jesse! – link664