2013-01-03 82 views
0

可有人能幫助我找到:模式不具約束力的行動

型號:

public class CreateAdCategoryViewModel 
{ 
    [Display(ResourceType = typeof(HeelpResources), Name = "AdViewModel_Category_Label")] 
    [Required(ErrorMessageResourceName = "AdViewModel_Required_ErrorMsg", ErrorMessageResourceType = typeof(HeelpResources))] 
    public int Category_Id { get; set; } 

    public IEnumerable<SelectListItem> CategoryList { get; set; } 

    public CreateAdCategoryViewModel(IEnumerable<SelectListItem> categoryList) 
    { 
     CategoryList = categoryList; 
    } 
} 

控制器:

[Authorize] 
    [HttpPost] 
    public virtual PartialViewResult CreateAdCategoryType(CreateAdCategoryViewModel model) 
    { 
     // Build the ViewModel to return to the View with the Category Drop List 
     return PartialView(new CreateAdCategoryTypeViewModel(CategoryDropDownList())); 
    } 

查看:

@model Heelp.ViewModels.CreateAdCategoryViewModel 

@using (Ajax.BeginForm(MVC.Ad.CreateAdCategoryType(), new AjaxOptions { UpdateTargetId = "category_type", InsertionMode = InsertionMode.Replace }, new { @id = "categoryForm" })) 
{ 
    @Html.DisplayNameFor(m => m.Category_Id) 
    @Html.DropDownListFor(m => m.Category_Id, Model.CategoryList, HeelpResources.DropdownlistCategoryFirstRecord) 
    @Html.ValidationMessageFor(m => m.Category_Id) 
} 

使用Javascript進行提交:

$(document).ready(function() 
{ 
    $("#Category_Id").change(function() 
    { 
     $("#categoryForm").submit(); 
    }); 
}); 

的這裏的問題是,提交從未發現的動作CreateAdCategoryType與模式參數,爲什麼呢?

+0

可能是因爲你的模型有參數化構造函數,MVC不知道如何調用它? –

+0

是的你是正確的,我脫下構造函數,一切正常,所以我怎麼能有一個構造函數來簡化模型返回到視圖使用不同的方法? – Patrick

回答

0

當談到進入控制器的模型時,他們需要成爲POCO。如果您沒有無參數構造函數,MVC框架根本不會知道如何創建實例。記住,它需要爲你的模型提供保溼。它不知道該怎麼辦

new CreateAdCategoryTypeViewModel(CategoryDropDownList()) 

它需要創建一個實例和發現(反映)所有的公共屬性和滋潤它。在你的情況下,即使它(框架)找到構造函數,它也不知道提供給它的數據。儘管我認爲它只查找無參數的構造函數。

+0

謝謝,所以你說ViewModels永遠不會有構造函數,只有公共屬性才能在數據到達Action時映射它們? – Patrick

+0

它必須是一個無參數的構造函數。既然你已經聲明瞭你的特殊構造函數,它不知道該如何處理它。嘗試顯式添加無參數的構造函數。但一般來說,這個模型應該是你的DTO,而不是別的。 –