views:

52

answers:

2

Hi all, 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:

<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!

A: 

Try specifying the name attribute as well:

<%= Html.TextBoxFor(m => m.Box.Name, new { id= "txtName", name = "txtName" }) %>
korchev
I tried this and the name attribute was still set to 'Box.Name'. Thanks for the suggestion though.
BFOT
+3  A: 

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'
        }
    }
});
Darin Dimitrov
Thanks for the explanation Darin. Looks like I need to better understand model binding. Adding quotes to the name did the trick and now client-side validation is working. Cheers!
BFOT