jquery 页面上的多个表单在 ASP.NET MVC 中进行了不显眼的验证

Multiple forms on page with jquery unobtrusive validation in ASP.NET MVC

JQuery 不显眼的验证似乎基于传递给页面的模型工作 - 但如果我想使用多个模型怎么办?

假设 "MyPage" 有两种形式,每种形式都回发到不同的 Action,具有不同的模型

型号

public class MyPageModel
{
    public List<Student> Students { get; set; }
    public List<Prof> Profs { get; set; }
    [Required]
    public string Student { get; set; } // wrong wrong wrong
    [Required]
    public string Prof { get; set; } // so wrong. this can't be the way
}

public class AddStudentModel 
{
    [Required]
    public string Student { get; set; }
}

public class AddProfModel 
{
    [Required]
    public string Prof { get; set; }
}

查看

// MyPage!

// list students here

@using (Html.BeginForm("AddStudent", "Controller", new { }, FormMethod.Post))
{
     @Html.TextBox("Student", null, new { })
     @Html.ValidationMessageFor("Student")
     <input type="submit" value="add student" />
}

// list professors here

@using (Html.BeginForm("AddProf", "Controller", new { }, FormMethod.Post))
{
     @Html.TextBox("Prof", null, new { })
     @Html.ValidationMessageFor("Prof")
     <input type="submit" value="add prof" />
}

控制器

public ActionResult MyPage()
{
    MyPageModel model = new MyPageModel(); 
    // bind data here
    return View(model);
}

public ActionResult AddStudent(AddStudentModel model)
{
    // add student
    return RedirectToAction("MyPage");
}

public ActionResult AddProf(AddProfModel model)
{
    // add professor
    return RedirectToAction("MyPage");
}

到目前为止,我一直在向 MyPageModel 添加空的 Student / Prof 属性,但这感觉很老套。有没有办法在 Html.BeginForm 中指定 jquery 验证将使用的模型?

您可以为此使用子操作,并从 MyPageModel 中删除额外的属性:

public ActionResult MyPage()
{
    MyPageModel model = new MyPageModel(); 
    // bind data here
    return View(model);
}

[HttpGet]
public ActionResult AddStudent()
{
    return PartialView(new AddStudentModel());
}

[HttpPost]
public ActionResult AddStudent(AddStudentModel model)
{
    //add student
    return RedirectToAction("MyPage");
}

当前我的页面:

//MyPage!
@Html.Action("AddStudent", "SomeController")

@Html.Action("AddProf", "SomeController")

新视图 return由新的子操作创建。

//AddStudent.cshtml

@using (Html.BeginForm())
{
     @Html.TextBoxFor(m => m.Student)
     @Html.ValidationMessageFor(m => m.Student)
     <input type="submit" value="add student" />
}

为了使它成为一个巧妙的解决方案,可能值得看看 Ajax.BeginForm,因为它允许您在页面上一次更新一个表单(并且 return 部分更新作为响应查看,因此表单提交不需要刷新整个页面)。