【问题标题】:How to keep a model datas if !ModelState.IsValid?如果!ModelState.IsValid,如何保留模型数据?
【发布时间】:2017-12-30 19:08:50
【问题描述】:

我是 MVC 的初学者,所以我为这个新手问题道歉:

如果用户没有正确填写表格,我想保留我的模型数据。

当我返回View(res) 时,有没有办法保留来自res 的数据?

感谢您的帮助

编辑:

NewReservationVM 类:

public class NewReservationVM
{
    int idRoom;
    string firstName;
    string lastName;
    DateTime checkin;
    DateTime checkout;
    decimal price;

    public int IdRoom { get => idRoom; set => idRoom = value; }
    [Required(ErrorMessage = "Veuillez saisir votre prénom.")]
    public string FirstName { get => firstName; set => firstName = value; }
    [Required(ErrorMessage = "Veuillez saisir votre nom.")]
    public string LastName { get => lastName; set => lastName = value; }
    [DisplayFormat(DataFormatString = "{0:dd/MM/yyyy}")]
    public DateTime Checkin { get => checkin; set => checkin = value; }
    [DisplayFormat(DataFormatString = "{0:dd/MM/yyyy}")]
    public DateTime Checkout { get => checkout; set => checkout = value; }
    public decimal Price { get => price; set => price = value; }
}

控制器:

[HttpPost]
    public ActionResult Create(NewReservationVM res)
    {
        if(ModelState.IsValid)
            return RedirectToAction("ResOk", res);

        return View(res);
    }

【问题讨论】:

  • 你能完整地编写你的视图模型“NewReservationVM”吗?
  • 您不应该在 res 实例上丢失值...请发布更多代码,因为问题可能不是您认为的...
  • 建议:在该控制器方法的第一行放置一个断点,并使用“quickwatch”检查“res”变量接收到的值。如果值在那里,当您调用“return View(res);”时您确实将所有接收到的值提供回视图(无论您的模型是否有效)。
  • 它实际上获得了初始值,因为如果 ModelState.IsValid 返回 true,我会在“ResOk”视图中检索它们。我的问题是只有当 ModelState.IsValid 为假时我才会丢失它们。它应该返回完全相同的视图,但由于某种原因我丢失了数据。
  • RedirectiToACtion("ResOk", res) doesn't do what you think it does.

标签: c# asp.net-mvc post modelstate


【解决方案1】:

我已将您的 ViewModel 类更改为:

public int IdRoom { get; set; }
[Required(ErrorMessage = "Veuillez saisir votre prénom.")]
public string FirstName { get; set; }
[Required(ErrorMessage = "Veuillez saisir votre nom.")]
public string LastName { get; set; }
[DisplayFormat(DataFormatString = "{0:dd/MM/yyyy}")]
public DateTime Checkin { get; set; }
[DisplayFormat(DataFormatString = "{0:dd/MM/yyyy}")]
public DateTime Checkout { get; set; }
public decimal Price { get; set; }

现在它可以按您的意愿工作了。另外,如果你想使用私有字段并实现set和set方法,正确的是这样:

private int idRoom;
public int IdRoom
{
  get { return idRoom; }
  set { idRoom = value; }
}

我不熟悉您使用的语法,但这是我所知道的最标准的语法,并且它正在工作。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2018-09-22
    • 1970-01-01
    • 2022-10-05
    • 1970-01-01
    • 1970-01-01
    • 2020-08-13
    • 2018-10-14
    相关资源
    最近更新 更多