我想了解MVC中的部分視圖... 我想要完成的是有一個主視圖,呈現兩個部分視圖。 每個局部視圖都包含不同的ViewModel(帶有DataAnnotations)。當我提交其中一個部分視圖的表單時,如果存在服務器端驗證錯誤,我希望主視圖再次顯示該部分的驗證消息。MVC部分視圖驗證
任何正確的方法提示將深表感謝。
我想了解MVC中的部分視圖... 我想要完成的是有一個主視圖,呈現兩個部分視圖。 每個局部視圖都包含不同的ViewModel(帶有DataAnnotations)。當我提交其中一個部分視圖的表單時,如果存在服務器端驗證錯誤,我希望主視圖再次顯示該部分的驗證消息。MVC部分視圖驗證
任何正確的方法提示將深表感謝。
在這裏你去樣品溶液 -
讓創建下列方式複雜的模型 -
public class Person
{
public Contact contact { get; set; }
public Vehicle vehicle { get; set; }
}
public class Contact
{
[Required]
public string Email { get; set; }
}
public class Vehicle
{
[Required]
public string Name { get; set; }
}
然後讓創建具有下列方式索引操作的主控制器,這個動作是怎麼回事創建一個簡單的假人模型,並將其綁定到索引視圖 -
public class MainController : Controller
{
public ActionResult Index()
{
Person p = new Person();
p.contact = new Contact();
p.vehicle = new Vehicle();
return View(p);
}
}
和索引視圖將是 -
@model MVC.Controllers.Person
@{
ViewBag.Title = "Index";
}
<h2>Index</h2>
@using (Html.BeginForm("Submit","Main",FormMethod.Post))
{
@Html.EditorFor(x => x.contact, "~/Views/Main/EditorTemplates/Contact.cshtml")
@Html.EditorFor(x => x.vehicle, "~/Views/Main/EditorTemplates/Vehicle.cshtml")
<input type="submit" value="click"/>
}
在上面的視圖中,我使用了編輯器視圖,而不是部分視圖。原因是部分視圖給模型綁定複雜模型帶來了非常困難的經驗。
因此,我在Main View文件夾中創建了EditorTemplated文件夾,並在其中放置了以下文件。
Contact.cshtml -
@model MVC.Controllers.Contact
@Html.LabelFor(model => model.Email, new { @class = "control-label col-md-2" })
@Html.EditorFor(model => model.Email)
@Html.ValidationMessageFor(model => model.Email)
Vehicle.cshtml -
@model MVC.Controllers.Vehicle
@Html.LabelFor(model => model.Name, new { @class = "control-label col-md-2" })
@Html.EditorFor(model => model.Name)
@Html.ValidationMessageFor(model => model.Name)
通過以上的設置,我們可以去運行應用程序,以下屏幕應顯示 -
這種形式是要發佈到提交主控制器的作用,所以這將是我的提交行動 -
public ActionResult Submit(Person p)
{
if (!ModelState.IsValid)
return View("Index", p);
else
{
// do something
return View();
}
}
當我們點擊按鈕,不輸入任何值,那麼驗證將觸發我們應該看到錯誤消息如下 -
,在正常有效的情況下,您可以提交表單,然後運行你的業務邏輯。
「我希望主視圖再次顯示該部分的驗證消息。」這是什麼意思? – Ehsan
我的意思是母版頁會再次顯示正確的驗證信息。 – HelderMPinhal
你有沒有嘗試不引人注目的客戶端驗證。這應該做你想要的。 –