对多个视图和控制器使用if-else的mvc替代方案

本文关键字:if-else mvc 方案 视图 控制器 | 更新日期: 2023-09-27 18:24:55

我想创建一个模型视图控制器,而不需要为单个控件设置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将不理解如何放置子属性。

多态模型绑定

对多个视图和控制器使用if-else的mvc替代方案

我不完全理解你的问题,但很好,很抱歉出现任何错误。

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);
}

CCD_ 3具有Thing1Model的模型

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

但是什么时候会在视图中(thing1),只使用:

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