【问题标题】:Getting Null value of date in controller from view by using view model使用视图模型从视图中获取控制器中日期的 Null 值
【发布时间】:2013-07-21 09:33:02
【问题描述】:

我是 MVC 的新手。我面临使用视图模型将出生日期值从视图获取到控制器的问题。我正在使用视图模型来获取表单值并获取所有其他文本框值。但我总是得到日期的空值。

我的视图模型是这样的。

  public class Student
  {
       [Required(ErrorMessage = "Date of birth is required")]
       [DataType(DataType.Date), DisplayFormat(ApplyFormatInEditMode = true,DataFormatString = "{0:dd/MM/yy}",ConvertEmptyStringToNull=false)]
       public DateTime? DateOfBirth { get; set; }
  }

表单发布后调用的控制器是:

 [HttpPost]
    public ActionResult StudentPersonalReg(Student stud)
    {
        DateTime? dateofbirth = stud.DateOfBirth;     
        return RedirectToAction("Registration");
    }

我的看法是

  @model eEducation.Models.UserModel.Student

   @Html.TextBoxFor(x => x.DateOfBirth)
   @Html.ValidationMessageFor(x => x.DateOfBirth)

问题是我总是在控制器中得到空值的日期。 当我从控制器调用视图时,我还尝试将 DateTime.Now 设置为视图模型。

我没有使用强类型视图。

请在这方面帮助我。

我通过控制器方法传递我的模型来查看

    public ViewResult Registration()
    {
        var db = new eEducationEntities();
        List<CountryMaster> queryCountry = db.CountryMasters.ToList();         

        List<StateMaster> queryState = db.StateMasters.ToList();


        Student stds = new Student();

        stds.Countries = queryCountry;
        stds.States = queryState;
        stds.DateOfBirth = DateTime.Now;

        return View("~/Views/UserSection/StudentRegistration.cshtml", stds);
    }

【问题讨论】:

  • 您是否真的将模型传递给您的视图?我看到的只是一个重定向(这与加载视图不同)。
  • 是的,我还将我的模型传递给由另一个控制器方法执行的视图
  • 我得到了问题的原因。那是因为文化。默认区域性为 en-US。我想要 dd/MM/yyyy 的日期。但还是找不到解决办法。如果我能够在主布局中设置文化信息,那么我认为它将引领解决方案。

标签: asp.net-mvc-3


【解决方案1】:

您需要在视图模型上使用 Html.BeginForm()。您甚至可以指定它发回的控制器操作。

@model eEducation.Models.UserModel.Student

@using (Html.BeginForm("StudentPersonalReg", "ControllerName")) {
    @Html.ValidationSummary(true)


   @Html.TextBoxFor(x => x.DateOfBirth)
   @Html.ValidationMessageFor(x => x.DateOfBirth)

<p>
            <input type="submit" value="Submit" />
        </p>
}

【讨论】:

  • 我已经在用这个了。如果我没有使用非表单,那么除了我已经提到的出生日期之外,我如何获得其他值。
  • 抱歉,但是,如果您不发布代码,我怎么知道您正在使用它?这么多人犯了这个错误,所以如果我没有相反的证据,我不能假设你没有。
  • 哦!不。你不需要道歉。只要解决这个问题。我会很感激你的。
猜你喜欢
  • 2012-04-09
  • 1970-01-01
  • 1970-01-01
  • 2020-03-25
  • 2011-03-16
  • 1970-01-01
  • 2015-02-22
  • 1970-01-01
  • 2018-12-15
相关资源
最近更新 更多