页面上有多个窗体,在ASP.NET MVC中使用jquery不显眼的验证

时间:2016-07-06 13:20:19

标签: jquery asp.net asp.net-mvc unobtrusive-validation

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");
}

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

1 个答案:

答案 0 :(得分:2)

您可以为此使用子操作,并从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:

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

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

新的子操作返回的新视图。

//AddStudent.cshtml

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

为了使其成为一个灵活的解决方案,可能值得一看Ajax.BeginForm,因为它允许您一次更新页面上的表单(并返回部分视图作为响应,以便表单提交不需要刷新整个页面。)