ASP.NET MVC 3 unobtrusive client-side validation with dynamic content

前端 未结 2 1196
星月不相逢
星月不相逢 2021-01-22 14:45

I have enabled unobtrusive client side validation in my app, and I have (something similar) to this model:

public class MyModel
{
    [Required]
    public strin         


        
相关标签:
2条回答
  • 2021-01-22 14:58

    Ahh... simple :)

    The @Html.BeginForm() must be in the same partial (which I guess is fair enough, since we are validating on a form), so:

    /Home/Index view becomes:

    @model MyModel
    
    <div id="my-form"> 
        @Html.Partial("Model")
    </div>
    

    With the partial "Model":

    @model MyModel
    
    @using (Html.BeginForm("Test", "Home"))
    {
        <div>
            @Html.LabelFor(x => x.Name)
            @Html.TextBoxFor(x => x.Name)
            @Html.ValidationMessageFor(x => x.Name)
        </div>
        <div>
            @Html.LabelFor(x => x.Age)
            @Html.TextBoxFor(x => x.Age)
            @Html.ValidationMessageFor(x => x.Age)
        </div>
    
        <input type="submit" value="Go" />
    }
    
    0 讨论(0)
  • 2021-01-22 15:16

    You dont need the form in your partial (theres an advantage at times to keeping it out, for ex. ajax forms and not having to rebind to a new form upon each load).

    In your partial simply add

    { ViewContext.FormContext = new FormContext()} 
    

    and the attributes will be written out.

    0 讨论(0)
提交回复
热议问题