標籤: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上進行多個模型的資料繫結