zoukankan      html  css  js  c++  java
  • MVC POST在ACTION上进行多个模型的数据绑定

    首先声明,接下来的东西并不符合本人认同的严谨的MVC模式。

    用MVC做项目的过程中,越来越多的用到不严谨的MVC编程。

    比如,在"cshtml"文件中写:

    @Html.Raw(DBUnitity.helperP.getNav("/main/Index",@ViewBag.token))

    做页面验证

    在比如,在"cshtml"文件中写:

    <div class="s-r">@DBUnitity.helperP.getSJCount("sj", "gz")</div>  做数据获取

    当然,这些代码不是我写的,是维护以前同事的代码。他的代码跑的好好的,我们也没去做优化,烂(懒)就烂(懒)下去吧。

    今天,要讲的,也是一种不严谨的MVC设计及实现的思路。

    我们有这样一个页面,比如需要往后台提交数据并进行处理,验证也好,更新也罢,但是提交的数据涉及到了数据库的多张表。

    如果按照之前我喜欢的模式,那么肯定是对页面Model进行封装,比如

     public class ViewModel
        {
            public LoginModel loginModel { set; get; }
            public PersonModel personModel { set; get; }
        }
    public class PersonModel
        {
            public string Age { set; get; }
            public string Other { set; get; }
        }
     public class LoginModel
        {
            public string Name { set; get; }
            public string Psd { set; get; }
        }

    然后在页面".cshtml"中这样写:

    @model  MvcBindDataDemo.ViewModel
    @using (Html.BeginForm())
    { 
        <p>
            账户:@Html.TextBoxFor(p => p.loginModel.Name)</p>
        <p>
            密码:@Html.PasswordFor(p => p.loginModel.Psd)</p>
        <p>
            年龄:@Html.TextBoxFor(p => p.personModel.Age)</p>
        <p>
            其他:@Html.TextBoxFor(p => p.personModel.Other)</p>
        
        <input type="submit" value="login" />
    }

    最后在Controller里面进行接收

      [HttpPost]
      public ActionResult Login(ViewModel obj)
      {
          xxx...
          return View();
      }

    //=========================================================================

    但是呢,或许我们也可以这样写

    不定义"ViewModel.cs"

    ".cshtml"里面

    @using (Html.BeginForm())
    { 
        <p>
            账户:@Html.TextBox("login.name", string.Empty)</p>
        <p>
            密码:@Html.Password("login.psd", string.Empty)</p>
        <p>
            年龄:@Html.TextBox("person.age", string.Empty)</p>
        <p>
            其他:@Html.TextBox("person.other", string.Empty)</p>
        
        <input type="submit" value="login" />
    }

    后台Controller:

     [HttpPost]
     public ActionResult Login( [Bind(Prefix = "login")]LoginModel objLogin,[Bind(Prefix="person")]PersonModel objPerson)
     {
          xxx...
          return View();
     }

    我们可以将数据直接绑定到“objLogin”与“objPerson”,数据拿到了,想做什么,随便了。

  • 相关阅读:
    LeetCode0350.两个数组的交集 II
    LeetCode0055.跳跃游戏
    LeetCode0739.每日温度
    LeetCode面试题46.把数字翻译成字符串
    LeetCode0128.最长连续序列
    LeetCode面试题29.顺时针打印矩阵
    LeetCode0238.除自身以外数组的乘积
    2020软件工程最后一次作业
    如何防止XSS攻击
    需求规格说明书
  • 原文地址:https://www.cnblogs.com/fri-yu/p/4142258.html
Copyright © 2011-2022 走看看