MVC POST在ACTION上進行多個模型的資料繫結

來源:互聯網
上載者:User

標籤:style   blog   http   io   ar   color   os   sp   for   

首先聲明,接下來的東西並不符合本人認同的嚴謹的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”,資料拿到了,想做什麼,隨便了。

 

MVC POST在ACTION上進行多個模型的資料繫結

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.