0

私はMVCが初めてです。ビューモデルを使用して、生年月日の値をビューからコントローラーに取得するという問題に直面しています。フォームの値を取得し、他のすべてのテキスト ボックスの値を取得するビュー モデルを使用しています。しかし、私は常に日付にnull値を取得します。

私のビューモデルはこんな感じです。

  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)

問題は、コントローラーの日付に対して常に null 値を取得することです。また、コントローラーからビューを呼び出すときに、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);
    }
4

1 に答える 1

0

ビューモデルで 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>
}
于 2013-07-22T09:11:39.020 に答える