开发者

Validation with Ajax and MVC

I am looking at the best way to take advantage of the MVC validation while using Ajax and not having access to a class.

On my masterpage it will contain a simple form (name, email, tel, comments) which I display in a overlay. As this is in the masterpage is available on any page, The masterpage never inherits a class like you would do when normally validating. So im not sure how (or if its still possible) to validate my form in the same way.

I thought creating a class with the same validation开发者_JAVA技巧 rules i would normally apply would help and then trying to maybe load this from viewdata? is this the best way to go or will validation not work doing this?


Server side validation will still work if you create a server side class with validation rules. But adding client input fields will have to be done manually and not using the view model:

<% using Html.BeginForm("ActionName", "Controller") %>
<% { %>
    <%= Html.TextBox("Name") %>
    <%= Html.TextBox("Email") %>
    <%= Html.TextBox("Phone") %>
    <%= Html.TextArea("CommentText") %>
<% } %>

Your controller action would look like:

[HttpPost]
public ActionResult ActionName(Comment comment)
{
    if (!this.Model.IsValid)
    {
        // handle model state exception
    }
    // save comment
    return // whatever needed
}

of course as long as you have a class:

public class Comment
{
    [Required]
    public string Name { get; set; }

    [RegularExpression(/* provide the email reg ex here */)]
    public string Email { get; set; }

    public string Phone { get; set; }

    [Required] // probably, but you'd know best
    public string CommentText { get; set; }
}

And while doing it I urge you to read my blog post about Asp.net MVC ajax and model validation, that may help you lots.

0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜