Pregunta

I am developing an application where I have a form with a model "StudentListModel".

I have a button in the same page which is not a submit button. I have written an ajax function which calls an action method in the controller specified.

Now my problem is there is a textbox for the studentname ,

    [StringLength(160, MinimumLength = 3)]
    [Display(Name = "First Name")]
    [Required]
    [Remote("CheckDuplicateNames", "AddStudent")]
    public string StudentName { get; set; } 

None of these validations are firing.However if I make the button as submit ,these will work.

Is there any way to do model validation other than using formsubmission?

¿Fue útil?

Solución

Model validation is done automatically before your ActionMethod is executed and ModelState will be populated with information about that validation. You do not need to call ValidateModel as long as you are running your Controller and ActionMethods in the default MVC lifecycle.

An action method that has parameters will have the values for parameters populated using MVC Model Binding. This means that any values posted in a Form or QueryString (and a few other sources) will be name matched to simple parameters or properties in complex parameters. Using an HTML form and the MVC HtmlHelper methods for creating input types you get the desired behavior with very little work, but as you have noted it requires a form submit to send the data.

An ajax call will also populate the model using Model Binding but it requires the fields to be sent to the ActionMethod. Using jQuery it is as simple as performing a post or get request on the buttons click event passing a JavaScript object with your model's properties on it.

$('#yourButtonId').click(function() {
    var student = {};
    student.StudentName = $('#StudentName').val();
    $.post('@Url.Action("ActionMethodName")', student).done(function (data) {
    //handle returned result from ActionMethod}
    });
});

Otros consejos

You can call model validation manually in the controller method. The syntax is simply ValidateModel(model). This validates the model based on its current property values, and populates the ModelState dictionary with any errors.

If your model does not get populated with the values, but you have got them at hand, you can populate it using UpdateModel(model, values), another method inherited from the Controller class.

Licenciado bajo: CC-BY-SA con atribución
No afiliado a StackOverflow
scroll top