2010-06-27 31 views
2

我對ASP.NET MVC相當陌生,而且Html.TextBoxFor()有一個問題 - 它給出了呈現的輸入的名稱屬性點。ASP.NET MVC - 停止Html.TextBoxFor向Name屬性添加一個點

<%= Html.TextBoxFor(m => m.Box.Name, new { id= "txtName" }) %> 

呈現以下HTML:

<input type="text" value="" name="Box.Name" id="txtName"> 

我使用jQuery驗證插件客戶端驗證。它不能驗證此輸入,因爲中的圓點框名稱(導致javascript錯誤)。

我的模型看起來是這樣的:

public class Box { 
    [Required(ErrorMessage = "Please enter a name")] 
    public string Name { get; set; } 
    public int BoxMaterialID { get; set; } 
} 

我的視圖模型是這樣的:

public class BoxViewModel 
{ 
    public Box Box { get; set; } 
    public List<BoxMaterial> BoxMaterial { get; set;} 
} 

我的控制器看起來是這樣的:

public ActionResult New(FormCollection postData) 
{ 
    Box box = new Box(); 

    try 
    { 
     UpdateModel(box, "Box"); 
     boxService.SaveBox(box); 
    } 
    catch 
    { 
     return View(new BoxViewModel(box)); 
    } 

    return RedirectToAction("Index", "Boxes"); 
} 

服務器端驗證那樣工作在模型上使用DataAnnotations的魅力。我似乎遇到的唯一問題是客戶端驗證,因爲「。」在name屬性中。

感謝您的幫助!

回答

6

的點加到名字時形式,以正確填充模型提交所使用的default model binder。就驗證而言,你可以這樣設置:

$("#myForm").validate({ 
    rules: { 
     'Box.Name': { 
      required: true 
     } 
    }, 
    messages: { 
     'Box.Name': { 
      required: 'some error message' 
     } 
    } 
}); 
+0

感謝Darin的解釋。看起來我需要更好地理解模型綁定。給名稱添加引號確實有用,現在客戶端驗證正在工作。乾杯! – cjacques 2010-06-27 21:45:49

0

嘗試指定屬性的名稱,以及:

<%= Html.TextBoxFor(m => m.Box.Name, new { id= "txtName", name = "txtName" }) %> 
+0

我試過這個,name屬性仍然設置爲'Box.Name'。 (還是)感謝你的建議。 – cjacques 2010-06-27 21:47:28

相關問題