2016-07-06 15 views
0

JQueryの邪魔されない検証は、ページに渡されたモデルに基づいて動作しているようですが、複数のモデルを再生したい場合はどうすればよいですか?ASP.NET MVCでjqueryの邪魔にならない検証がページ上に複数のフォーム

それぞれが異なるモデルと、別のアクションに戻って

モデル

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"); 
} 
を掲示する、のは、 "マイページ" は、2つのフォームを持っているとしましょう

これまでは空のStudent/Profの属性をMyPageModelに追加しましたが、これは非常にハッキリです。 jqueryの検証で使用されるモデルをHtml.BeginFormに指定する方法はありますか?

答えて

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! 
@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見てみる価値がある(とREPONSEとして部分ビューを返すことがありますフォーム提出はページ全体をリフレッシュする必要はありません)。

関連する問題