Warning: file_get_contents(/data/phpspider/zhask/data//catemap/0/asp.net-mvc/14.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C# 如果ModelState无效,则在mvc post之间持久化dropdownlist_C#_Asp.net Mvc_Persistence_Viewmodel - Fatal编程技术网

C# 如果ModelState无效,则在mvc post之间持久化dropdownlist

C# 如果ModelState无效,则在mvc post之间持久化dropdownlist,c#,asp.net-mvc,persistence,viewmodel,C#,Asp.net Mvc,Persistence,Viewmodel,我有一个保存以下实体的简单表单 public class TravelInfo{ public int ID {get;set;} public string CentreCode {get;set;} public DateTime TravelDate {get;set;} } 我在我的控制器中有标准的2个创建方法-1 get 1 post,我使用这个viewmodel将内容放入视图中 public class TravelInfoVM{ public TravelInfo

我有一个保存以下实体的简单表单

public class TravelInfo{
  public int ID {get;set;}
  public string CentreCode {get;set;}
  public DateTime TravelDate {get;set;}
}
我在我的控制器中有标准的2个创建方法-1 get 1 post,我使用这个viewmodel将内容放入视图中

public class TravelInfoVM{
  public TravelInfo TravelInfo{get;set;}
  public IEnumerable<SelectListItem> Centres {get;set;}
}

问题是,如果ModelState返回为无效,我真的需要第二次往返DB以获取中心列表吗?或者,是否有更好的/不同的方法在帖子中保留此列表,直到用户正确输入保存所需的详细信息。。?或者我的棍子末端完全错了。

如果不将其添加到会话中,这是对会话的不当使用。否则,每个请求都是一个独特的雪花,即使它看起来是一样的,因为您返回的表单有错误

我不担心这个。这只是一个查询,而且由于它是以前发出的同一个查询,它很可能(或者至少可以)被缓存,因此无论如何,它实际上可能不会命中数据库

不过,我建议您对查询进行抽象,以便GET和POST操作只需调用一个不会更改的函数,如果您需要更改选择列表的创建方式,只需在一个位置执行此操作:

internal void PopulateCentreChoices(TravelInfoVM model)
{
    model.Centres = db.Centres.Select(c=> new SelectListItem {Text = c.Name, Value = c.Code}).ToList();
}

...

public ActionResult Create(){
  var model = new TravelInfoVM();
  PopulateCentreChoices(model);
  return View(model);
}

[HttpPost]
public ActionResult Create(TravelInfoVM model){
  if(ModelState.IsValid){
    //save
    //redirect
  }
  PopulateCentreChoices(model);
  return View(model);
}

非常感谢-在我进行此操作时,如何在重新加载时使日期停止默认为01/01/0001?对于日期,我总是在视图模型属性上使用
DateTime?
。通过允许
null
,如果没有发布任何内容,则日期将保持空白。如果需要,则添加
[required]
属性仍然有效,如果实体只接受
日期时间
,则您仍然可以将过账值保存到实体中,只要您要求用户在某个时间输入一些值即可。
internal void PopulateCentreChoices(TravelInfoVM model)
{
    model.Centres = db.Centres.Select(c=> new SelectListItem {Text = c.Name, Value = c.Code}).ToList();
}

...

public ActionResult Create(){
  var model = new TravelInfoVM();
  PopulateCentreChoices(model);
  return View(model);
}

[HttpPost]
public ActionResult Create(TravelInfoVM model){
  if(ModelState.IsValid){
    //save
    //redirect
  }
  PopulateCentreChoices(model);
  return View(model);
}