2014-09-29 20 views
2

我想創建一個模型視圖控制器,而不必爲單個控件設置if-else,或者不得不復制這些控件以處理不同的屏幕控件。
目前我有: -mvc替代多個視圖和控制器使用if-else

//控制器

public ActionResult DisplayThing1(int thingType, string thingName){ 

    Thing1Model model = new Thing1Model(); 
    return View(model); 
} 

[HttpPost] 
public ActionResult DisplayThing1(Thing1Model model) 
{ 
    Save(model); 
    return RedirectToAction("DisplayThing1"); 
} 

//模型

public class Thing1Model() 
{ 
public int type {get; set; } 
public string Name {get; set;} 
} 

//視圖

@using(Html.BeginForm(....)) 
{ 
@Html.HiddenFor(m=>m.type); 
@Html.LabelForI(m=>m.Name); 
} 

我已經幾乎複製控制器Thing2Model,該模型本身是

public class Thing2Model() 
{ 
public int type {get; set; } 
public string Name {get; set;} 
public DateTime MyDate {get; set;} 
} 

組合視圖如下所示。

@using(Html.BeginForm(....)) 
{ 
@Html.HiddenFor(m=>m.type); 
@Html.LabelForI(m=>m.Name); 
@if(type == "2") 
{ 
    @Html.TextBoxFor(m=>m.MyDate); 
} 
} 

我找一個更好的選擇,以避免@if以及重複的代碼

編輯: 添加到@ W92的答案。我們還需要更改模型聯編程序以支持繼承模型。 否則,在這段代碼的視圖中,MVC不會理解如何放置子屬性。

Polymorphic model binding

+1

您試圖使用partialVie w或Html.Action()? (它返回PartialView)。在Html.Action中你可以放置一個參數等等。聽起來很不錯。對於服務Html.Action good的使用屬性的操作:'[ChildActionOnly()]'(在谷歌中讀取)或要求更多詳細信息:-) – W92 2014-09-29 15:23:18

+0

我想使用局部視圖,但常見字段需要顯示在不常見的。請參閱http://www.gliffy.com/go/publish/image/6238620/L.png。我如何用局部視圖來做到這一點? – heyNow 2014-09-29 15:37:22

+0

我不明白這個問題,你能詳細解釋一下嗎? – W92 2014-09-29 19:28:17

回答

1

我完全不明白你的問題,但還不錯,還有對任何錯誤抱歉。

public class Thing1Model() 
{ 
public int type {get; set; } 
public string Name {get; set;} 
} 

public class Thing2Model() : Thing1Model 
{ 
    public DateTime MyDate {get; set;} 
} 

,並在您查看:// MODEL2

@using(Html.BeginForm(....)) 
{ 
    @Html.PartialView("_myForm"); 
     @Html.TextBoxFor(m=>m.MyDate); 
} 

_myForm有Thing1Model與內容的模型:

@Html.HiddenFor(m=>m.type); 
@Html.LabelForI(m=>m.Name); 

但是當將在視圖(thing1),只使用:

@using(Html.BeginForm(...)) 
{ 
@Html.PartialView("_myForm"); 
} 
+0

好!我沒有想到這一點。那麼1)控制器只使用父模型來獲取,發佈? 2)視圖可以在父模型上強類型嗎? – heyNow 2014-09-29 20:23:43

+1

模型用於呈現您的數據(文本框,標籤等)。它只返回唯一的html。在f12瀏覽器上測試它。這是一個必要的信息。我更喜歡你用microsoftacademy學習:-)這裏有三個偉大的課程(一個來自其他網站): http://www.microsoftvirtualacademy。com/training-courses/introduction-to-asp-net-mvc http://www.microsoftvirtualacademy.com/training-courses/developing-asp-net-mvc-4-web-applications-jump-start 和 http://pluralsight.com/training/Player?author=scott-allen&name=mvc4-building-m6-ajax&mode=live&clip=0&course=mvc4-building 真的很值得! :-) – W92 2014-09-29 20:29:30

相關問題