0

I have used this solution of rendering a view into a string successfully until I had to do the validation. This is on the view:

@Html.TextBoxFor(m => m.OrderedQuantity, new { id="someid", name="somename", data_mini = "true", type = "number", @class = "orderedQuantity removeGroupsRequired" })

and what the result is:

<input class="orderedQuantity removeGroupsRequired" data-mini="true" data-val="true" data-val-number="The field Quantity:  must be a number." data-val-required="The Quantity:  field is required." id="someid" name="OrderedQuantity" type="number" value="0" />

and I need the name in order do make some rules for an unobtrusive validation:

var form = $("#mydiv form");
form.validate(
    {
        rules: {
            somename: {
                required: true
            }
        },
        messages: {
            somename:
                {
                    required: "you must provide a quantity!"
                }
        }
    }
);
Community
  • 1
  • 1
bokkie
  • 1,477
  • 4
  • 21
  • 40

1 Answers1

0

You cannot set the name attribute when using the TextBox helper. That's by design. So don't try it. This helper is designed to generate markup with input field names matching your view model properties so that when the form is submitted the default model binder will be able to bind the corresponding value to the property on the view model:

@Html.TextBoxFor(
    m => m.OrderedQuantity, 
    new { 
        id = "someid",   
        data_mini = "true", 
        type = "number", 
        @class = "orderedQuantity removeGroupsRequired" 
    }
)

The name of the input field is OrderQuantity, so that's what you should use for your validation rules:

form.validate({
    rules: {
        OrderedQuantity: {
            required: true
        }
    },
    messages: {
        OrderedQuantity: {
            required: "you must provide a quantity!"
        }
    }
});

If you want to be able to use custom name, different than what the correct name for the model binding would have been (OrderedQuantity), then you will have to either write a custom helper or hardcode the markup (both are totally non-recommended solutions).

Darin Dimitrov
  • 1,023,142
  • 271
  • 3,287
  • 2,928
  • ok, thanks, though the rules still didn't apply...and I am close to throwing my laptop out the window :)) this is how it looks , nothing changed... – bokkie Sep 10 '13 at 11:18