【问题标题】:Two forms and one viewmodel两种形式和一种视图模型
【发布时间】:2013-03-05 01:07:31
【问题描述】:

我在一页中有两个表格。两者都有自己的属性和提交操作,但在两种表单中都有一些共同的属性。

有没有办法使用一个视图模型来构建具有两个表单的视图,该视图模型与视图中的两个表单共享属性?

实际上我有重复的字段,我必须使用 jquery 复制两个字段中值的更改。

谢谢。

【问题讨论】:

  • 可以通过不同的BindingPrefix来实现。请看下面我的回答

标签: c# asp.net-mvc model viewmodel


【解决方案1】:

您可以使用 HtmlPrefix 来实现这一点。

  1. 我已经创建了一个模型

    public class TestModel
    {
      [Required]
      public int Id { get; set; }
      [Required]
      public string Name { get; set; }
    }
    
  2. 在 Controller 中,我们需要为每个表单设置一个 GetMethod 和两个 post 方法,但使用不同的 BindPrefix

    public ActionResult TestLoad()
    {
        TestModel model = new TestModel();
        return View(model);
    }
    
    public ActionResult TestA([Bind(Prefix = "A")]TestModel model)
    {
        return View("TestLoad",model);
    }
    public ActionResult TestB([Bind(Prefix="B")]TestModel model)
    {
        return View("TestLoad",model);
    }
    
    1. 在视图中。这里也我们需要指定绑定前缀
    <table>
     <tr>
      <td>
        @{Html.ViewData.TemplateInfo.HtmlFieldPrefix="A";}
        @{Html.RenderPartial("PartialA");}
      </td>
      <td>
        @{Html.ViewData.TemplateInfo.HtmlFieldPrefix="B";}
        @{Html.RenderPartial("PartialB");}
      </td>
    </tr>
    </table>
    
    1. 两个部分视图完全相同,只是它们将数据发布到不同的操作(在控制器中定义)

    2. 现在,如果您运行该项目,您应该会得到适当的输出。

【讨论】:

  • 嗨,谢谢,但我认为我的问题有点不同。想象一下,你的模型中有Name1和Name2,Name1用在PartialA和PartialB,Name2只用在PartialB,你的代码怎么实现呢?
猜你喜欢
  • 2013-12-13
  • 1970-01-01
  • 1970-01-01
  • 2011-09-28
  • 1970-01-01
  • 2013-06-12
  • 1970-01-01
  • 2011-02-03
  • 1970-01-01
相关资源
最近更新 更多