【问题标题】:asp.net mvc : custom ViewModel form postasp.net mvc:自定义 ViewModel 表单发布
【发布时间】:2009-07-31 14:53:57
【问题描述】:

刚开始使用 ASP.NET MVC,已经遇到了一个绊脚石。

情况是我有一个自定义 ViewModel 传递给视图,其中包含要评分的项目列表(将使用 jQuery 星级评分),因此这些是使用单选按钮帮助器创建的,具有相同的名称,只是不同的值,这些都没有问题。

但是,我完全不知道如何将其实际恢复到我的操作的发布版本中。我只是得到一个“无参数构造函数”错误。我不想使用表单集合 - 我希望我的数据保持基于类。

有没有人做过类似的事情?

非常感谢您的建议。

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

更新(包括基本代码):

    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" />
<% } %>               

【问题讨论】:

    标签: jquery asp.net-mvc


    【解决方案1】:

    尝试为 ViewModel 使用无参数构造函数。此外,属性的名称需要与控件的名称/ID 匹配。

    您可能需要稍微简化一下,甚至编写自己的模型绑定器。

    模型绑定器及其使用说明here

    一篇关于编写模型活页夹的好文章here

    我认为您需要编写自己的活页夹,因为您正在尝试构建一个复杂类型的数组。它本身的复杂类型会很好,它是数组中问题开始的地方。

    祝你好运!

    【讨论】:

    • 啊,成功的甜美气息……我不需要做任何复杂的事情,比如使用自定义模型绑定器,我只是在索引 rabiobutton 循环中使用了错误的属性名称。知道它不会那么困难......现在我只需要弄清楚如何拥有一个默认单选按钮,所以我不需要验证。干杯!
    【解决方案2】:

    当您的表单被发布时,只有选定的单选按钮值将被发布回服务器。

    您应该能够使用UpdateModel() 方法使用从表单回传的值自动更新您的模型类。

    【讨论】:

    • 我什至无法达到这一点。在帖子的操作中,我传递了一个我给视图的类的实例,但是在提交表单时它出现了上面的运行时错误。
    猜你喜欢
    • 2017-01-18
    • 2023-04-09
    • 1970-01-01
    • 1970-01-01
    • 2011-08-21
    • 2011-01-15
    • 2019-08-01
    • 1970-01-01
    • 2011-05-23
    相关资源
    最近更新 更多