1
在Edit
視圖中的代碼中,出現正確的供應商名稱文本,但是當我將其空白文本框並按下保存時,不會驗證它。賣方是Order模型的一個屬性,VendorName是Vendor模型中的一個屬性。它們以引用方式相關。我的表單並不是全部輸入到單個表格中,而是也輸入到衛星表格中。ASP.Net MvC框架,Html.ValidationMessage標記
<%= Html.TextBox("Vendor.VendorName")%>
<%= Html.ValidationMessage("Vendor.VendorName")%>
爲什麼驗證不會發生?
這似乎是工作,但它似乎是一個黑客對我說:
using M = HelloUranus.Models
//...
namespace HelloUranus.Controllers
{
public class OrderDetailController : Controller
{
//...
private M.DBProxy db = new M.DBProxy();
[AcceptVerbs(HttpVerbs.Post)]
public ActionResult Edit(int id, FormCollection collection)
{
//...
var orderDetail = db.GetOrderDetail(id);
//...
try
{
if (string.IsNullOrEmpty(Request.Form["Vendor.VendorName"]))
{
throw new Exception();
}
UpdateModel(orderDetail);
db.Save();
return RedirectToAction("Details", new {id = orderDetail.odID });
}
catch
{
ModelState.AddRuleViolations(orderDetail.GetRuleViolations());
return View(orderDetail);
}
//...
}
//...
}
ModelState.AddModelError自動將IsValid設置爲false。 – 2009-08-20 20:10:55
你說得對,我的錯。我知道你必須記住* something *,但是有一點需要設置ModelStateDictionary,使用SetModelValue將無效數據重新填充到表單中。讓我編輯出來。 – JoshJordan 2009-08-20 20:14:56
在工作流程中,我會執行ModelState.AddModelError(「Vendor.VendorName」,「*」)?如果在edit-post操作方法的Save部分的try部分完成,它會拋出一個異常,因爲ModelState.IsValid變爲false。 – JonathanWolfson 2009-08-20 20:21:29