0

I have a @Html.ValidationMessageFor(model => model.FirstName) in Partial view that is not functioning properly. The text box's contained within the loaded Partial View have the "Required" Data Annotation on them and the associated message displays right away. How can I avoid this? It doesn't even validate.

Partial View Code

@{ Html.EnableClientValidation(); }
@*@{ ViewContext.FormContext = new FormContext(); }*@
@using (Html.BeginForm("ActionName", "ControllerName"))
{

<div>
    @Html.TextBoxFor(model => model.FirstName)
    @Html.ValidationMessageFor(model => model.FirstName)
</div>
....//some more HTML
}

Main View Code

<div class="modal" id="modalId" role="dialog">
    <div class="modal-dialog">
        <div class="modal-content">
            <div class="modal-header">

            </div>
            <div class="modal-body" id="modalbodyId">
                @Html.Partial("PartilViewName")
            </div>
            <div class="modal-footer">

            </div>
        </div>
    </div>
</div>

I have tried the following things so far.
1. Added the following line of code in Partial View

@{ ViewContext.FormContext = new FormContext(); }    

2.Both ClientValidationEnabled and UnobtrusiveJavaScriptEnabled are set to true in web.config

3.Added the following script tags in BundleConfig.cs

<script src="@Url.Content("~/Scripts/jquery.validate.min.js")" type="text/javascript"></script>
<script src="@Url.Content("~/Scripts/jquery.validate.unobtrusive.min.js")" type="text/javascript"></script>

In all the posts that I have seen I need to use an AJAX call like the below code. However I am not sure on how to use it.

 $("#create").click(function () {
            var form = $("#create_person").closest("form");
            form.removeData('validator');
            form.removeData('unobtrusiveValidation');
            $.validator.unobtrusive.parse(form);

            $.ajax({
                url: "/Person/CreateOrUpdate",
                type: "POST",
                data: $("#create_person").serialize(),
                cache: false
            });


        });

Code Courtsey

Community
  • 1
  • 1
user2322507
  • 141
  • 1
  • 5
  • 19

1 Answers1

0

Try adding the model you use for your partial view as a property in the model of the view the partial is created in.

public class MainViewModel
{
    // properties

    public PartialViewModel PartialVm { get; set; }
}

Then when you render your partial, pass it the PartialViewModel property.

@Html.Partial("PartialViewName", Model.PartialVm)
JB06
  • 1,881
  • 14
  • 28