首页 \ 问答 \ 什么是适当的方法从MVC4中的视图将2个不同的模型传递给控制器(Whats the Appropriate Method to pass 2 different Models to the Controller from a View in MVC4)

什么是适当的方法从MVC4中的视图将2个不同的模型传递给控制器(Whats the Appropriate Method to pass 2 different Models to the Controller from a View in MVC4)

我正在使用SimpleCmbership的MVC4。 MVC设置了我的UserProfile表,我修改了注册视图以适应我的布局。 一切都很顺利,直到我确定我想要从我的用户那里包含一些最适合其他现有模型的附加信息。

通常,我将多个模型从View传递给Controller的方法是使用元组。 从历史上看,这对我来说非常有用,直到现在我还没有遇到任何实际问题。

我的注册表格类似于:

@model Tuple<MyNamespace.Models.RegisterModel,MyNamespace.Models.MembershipDetail>

@using (Html.BeginForm(new { ReturnUrl = ViewBag.ReturnUrl })) {
@Html.AntiForgeryToken()     
    <table style="border-collapse: collapse; border-spacing:0px; border-width:0px; margin: 0px; width:100px; padding: 0 0 0 0px; background-color:#2e2e2e;">
        <tr>
           <td>
              Profile Name
           </td>
           <td>
              @Html.TextBoxFor(m => m.Item2.ProfileName)
           </td>
        </tr> 
        <tr>
           <td>
              @Html.LabelFor(m => m.Item1.UserName)
           </td>
           <td>
              @Html.TextBoxFor(m => m.Item1.UserName)
           </td>
        </tr>
        <tr>
           <td>
              @Html.LabelFor(m => m.Item1.Password)
           </td>
           <td>
              @Html.PasswordFor(m => m.Item1.Password)
           </td>
        </tr>
        <tr>
           <td>
              @Html.LabelFor(m => m.Item1.ConfirmPassword)
           </td>
           <td>
              @Html.PasswordFor(m => m.Item1.ConfirmPassword)
           </td>
        </tr>                               
        <tr>
           <td>
              <button type="submit" id="btnSubmitForm" value="Register">Register</button>
           </td>
        </tr>
     </table>
     @Html.Partial("_ValidationSummary",ViewData.ModelState)                             
   }    

我的控制器的注册方法类似于:

    [HttpPost]
    [AllowAnonymous]
    [ValidateAntiForgeryToken]
    public ActionResult Register(RegisterModel model, MembershipDetail member)
    {
        if (ModelState.IsValid)
        {
            try
             {
                // Do something with the data
             }
            catch(MembershipCreateUserException e)
            {
               ModelState.AddModelError("",ErrorCodeToString(e.StatusCode));
            }
        }
        return View(model);
    }

每当我在单击Submit按钮后调试此代码时,我都会注意到返回到控制器的两个Models都是空的。 包含的字段是null,0或Empty Strings,我无法弄清楚原因。

为了增加这个谜团,如果我从视图的顶部删除元组并将其重新分配为单个模型,如下所示:

@model MyNamespace.Models.RegisterModel

并使用1 Model推断引用(m.Property等)替换代码中的元组引用(egmItem1.Property,m.Item2.Property); 然后将从TextBox助手传入的数据适当地分配给模型,并在调试代码时填充模型。

现在,我知道我可以简单地在UserProfile表中添加一些其他字段,并在我的模型中使用它们来完全缓解元组,但后来我复制了我的模式中的数据,这不是一个理想的解决方案。 请记住,尽管此处提供的示例代码仅包含第二个模型的1个元素,但它实际上将超过1个。

那么为什么在使用Tuple时不会填充模型,是否有更合适的方法来解决这个问题? 或者我不能在单个表单提交中混合模型数据???


I am using MVC4 with SimpleMembership. MVC has setup my UserProfile table and I've modified the Registration View to accomodate my layout. Everything worked great until I determined that I wanted to include some additional information from my user that best fit within the context of another already existing Model.

Typically my approach to passing more than one Model from my View to the Controller has been to employ Tuples. Historically this has worked out great for me and I've never had any real issues until now.

My Registration Form resembles this:

@model Tuple<MyNamespace.Models.RegisterModel,MyNamespace.Models.MembershipDetail>

@using (Html.BeginForm(new { ReturnUrl = ViewBag.ReturnUrl })) {
@Html.AntiForgeryToken()     
    <table style="border-collapse: collapse; border-spacing:0px; border-width:0px; margin: 0px; width:100px; padding: 0 0 0 0px; background-color:#2e2e2e;">
        <tr>
           <td>
              Profile Name
           </td>
           <td>
              @Html.TextBoxFor(m => m.Item2.ProfileName)
           </td>
        </tr> 
        <tr>
           <td>
              @Html.LabelFor(m => m.Item1.UserName)
           </td>
           <td>
              @Html.TextBoxFor(m => m.Item1.UserName)
           </td>
        </tr>
        <tr>
           <td>
              @Html.LabelFor(m => m.Item1.Password)
           </td>
           <td>
              @Html.PasswordFor(m => m.Item1.Password)
           </td>
        </tr>
        <tr>
           <td>
              @Html.LabelFor(m => m.Item1.ConfirmPassword)
           </td>
           <td>
              @Html.PasswordFor(m => m.Item1.ConfirmPassword)
           </td>
        </tr>                               
        <tr>
           <td>
              <button type="submit" id="btnSubmitForm" value="Register">Register</button>
           </td>
        </tr>
     </table>
     @Html.Partial("_ValidationSummary",ViewData.ModelState)                             
   }    

The Register Method of my Controller is similar to this:

    [HttpPost]
    [AllowAnonymous]
    [ValidateAntiForgeryToken]
    public ActionResult Register(RegisterModel model, MembershipDetail member)
    {
        if (ModelState.IsValid)
        {
            try
             {
                // Do something with the data
             }
            catch(MembershipCreateUserException e)
            {
               ModelState.AddModelError("",ErrorCodeToString(e.StatusCode));
            }
        }
        return View(model);
    }

Whenever I debug this code after the click of the Submit button, I note that both Models returned to the controller are empty. The contained fields are either null, 0 or Empty Strings and I cannot figure out why.

To add to this mystery, if I remove the tuple from the top of the view and re-assign it as a single Model as such:

@model MyNamespace.Models.RegisterModel

And replace the tuple references from the code (e.g. m.Item1.Property, m.Item2.Property) with the 1 Model inferred reference (m.Property and etc); then the data passed in from the TextBox helpers is appropriately assigned to the model and the model is populated when I debug the code.

Now, I know I could simply add a few other fields to the UserProfile table and use them in my Model to alleviate the Tuple altogether but then I am duplicating data in my schema which is not an ideal solution. And keeping in mind that though my sample code provided here only contains 1 element of the 2nd Model, it will actually be more than 1.

So why don't the Models get populated when using the Tuple and is there a more appropriate way to go about solving this problem? Or can I not mix Model data on a single form submission???


原文:https://stackoverflow.com/questions/23875456
更新时间:2023-01-06 20:01

相关问答

更多

相关文章

更多

最新问答

更多
  • 获取MVC 4使用的DisplayMode后缀(Get the DisplayMode Suffix being used by MVC 4)
  • 如何通过引用返回对象?(How is returning an object by reference possible?)
  • 矩阵如何存储在内存中?(How are matrices stored in memory?)
  • 每个请求的Java新会话?(Java New Session For Each Request?)
  • css:浮动div中重叠的标题h1(css: overlapping headlines h1 in floated divs)
  • 无论图像如何,Caffe预测同一类(Caffe predicts same class regardless of image)
  • xcode语法颜色编码解释?(xcode syntax color coding explained?)
  • 在Access 2010 Runtime中使用Office 2000校对工具(Use Office 2000 proofing tools in Access 2010 Runtime)
  • 从单独的Web主机将图像传输到服务器上(Getting images onto server from separate web host)
  • 从旧版本复制文件并保留它们(旧/新版本)(Copy a file from old revision and keep both of them (old / new revision))
  • 西安哪有PLC可控制编程的培训
  • 在Entity Framework中选择基类(Select base class in Entity Framework)
  • 在Android中出现错误“数据集和渲染器应该不为null,并且应该具有相同数量的系列”(Error “Dataset and renderer should be not null and should have the same number of series” in Android)
  • 电脑二级VF有什么用
  • Datamapper Ruby如何添加Hook方法(Datamapper Ruby How to add Hook Method)
  • 金华英语角.
  • 手机软件如何制作
  • 用于Android webview中图像保存的上下文菜单(Context Menu for Image Saving in an Android webview)
  • 注意:未定义的偏移量:PHP(Notice: Undefined offset: PHP)
  • 如何读R中的大数据集[复制](How to read large dataset in R [duplicate])
  • Unity 5 Heighmap与地形宽度/地形长度的分辨率关系?(Unity 5 Heighmap Resolution relationship to terrain width / terrain length?)
  • 如何通知PipedOutputStream线程写入最后一个字节的PipedInputStream线程?(How to notify PipedInputStream thread that PipedOutputStream thread has written last byte?)
  • python的访问器方法有哪些
  • DeviceNetworkInformation:哪个是哪个?(DeviceNetworkInformation: Which is which?)
  • 在Ruby中对组合进行排序(Sorting a combination in Ruby)
  • 网站开发的流程?
  • 使用Zend Framework 2中的JOIN sql检索数据(Retrieve data using JOIN sql in Zend Framework 2)
  • 条带格式类型格式模式编号无法正常工作(Stripes format type format pattern number not working properly)
  • 透明度错误IE11(Transparency bug IE11)
  • linux的基本操作命令。。。