开发者

ASP.NET MVC - Stop Html.TextBoxFor adding a dot to the Name attribute

I'm fairly new to ASP.NET MVC and I've got a problem with Html.TextBoxFor() - it's giving the rendered input's name attribute a dot.

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

renders the following HTML:

&l开发者_StackOverflow社区t;input type="text" value="" name="Box.Name" id="txtName">

I'm using the jQuery Validation plugin for client-side validation. It can't validate this input because of the dot in Box.Name (causes a javascript error).

My Model looks like this:

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

My ViewModel looks like this:

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

My Controller looks like this:

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

Server-side validation is working like a charm using DataAnnotations on the Model. The only problem I seem to be having is with the client-side validation because of the "." in the name attribute.

Thanks for your help!


The dot added to the name is used by the default model binder when the form is submitted in order to correctly populate the model. As far as validation is concerned you could set it like this:

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


Try specifying the name attribute as well:

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

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜