2009-07-31 39 views
3

剛開始使用ASP.NET MVC,已經遇到了一個絆腳石。asp.net mvc:自定義ViewModel表單帖子

這種情況是我有一個自定義的ViewModel傳遞給視圖,其中包含要評估的項目列表(將使用jQuery星級評分),所以這些都是使用單選按鈕助手創建的,相同的名稱,只是不同的價值,而這些渲染沒有問題。

但是,我完全不知道如何實際回到我的行動的後期版本。我只是得到'沒有參數的構造函數'錯誤。我不想使用表單集合 - 我希望我的數據保持基於類的。

有沒有人需要做類似的事情?

非常感謝您的任何建議。

============================================== =========================

UPDATE(包括基本代碼):

In the HomeController: 

    public class MyViewModel 
    { 
     public MyViewModel(List<Thing> things) // Thing.cs contains properties name and rating 
     { 
      this.Things = things;   
     } 

     public List<Thing> Things { get; private set; } 
    } 


    public ActionResult Index() 
    { 
     List<Thing> things = new List<Thing>(); 

     Thing t; 

     t = new Thing(); 
     t.name = "One"; 
     t.rating = 1; 
     things.Add(t); 

     t = new Thing(); 
     t.name = "Two"; 
     t.rating = 2; 
     things.Add(t); 

     return View(new MyViewModel(things)); 
    } 

    [AcceptVerbs(HttpVerbs.Post)] 
    public ActionResult Index(MyViewModel vm) 
    { 
     return View(); 
    }  

    and in the Index page (Inherits="System.Web.Mvc.ViewPage<MyProject.Controllers.MyViewModel>") 

<% using (Html.BeginForm()) 
    {%> 
    <ul> 
    <% for(int t = 0; t<Model.Things.Count; t++) 
     {%> 
      <li> 
       <% for (int i = 1; i < 6; i++) 
        { 
         MyProject.Thing thing = Model.Things[i]; 
         %> 
       <%=Html.RadioButton(String.Format("Things[{0}]", t), i)%> 
        <% } %> 

      </li> 
    <% }%> 
    </ul>  
    <input type="submit" value="submit me" /> 
<% } %>    

回答

3

嘗試使用ViewModel的無參數構造函數。此外,屬性的名稱需要與控件的名稱/ ID匹配。

您可能需要簡化一點,甚至可以編寫自己的模型綁定器。

模型活頁夾的說明及其使用here

上寫一個模型綁定here一篇好文章。

我認爲你需要編寫自己的綁定器,因爲你正在嘗試構建一個複雜類型的數組。它自己的複雜類型可以很好,它是陣列中問題開始的地方。

祝你好運!

0

當你的形式張貼,只所選的單選按鈕值將被髮回到服務器。

您應該能夠使用UpdateModel()方法與張貼從形式到的值自動更新您的模型類。

+0

雖然我甚至無法達到這一點。 在帖子的操作中,我傳遞了一個我給視圖的類的實例,但是當提交表單時,它有上面的運行時錯誤。 – Paul 2009-07-31 15:27:39

+0

你能發佈你的代碼嗎?這可能是一個稍微不相關的問題.. – womp 2009-07-31 15:54:24