Donate

@Html.ValidationMessageFor Will Always Show Or Display Error Message On Page Load In ASP.NET MVC

Good afternoon!

Given that you have a HTML form loaded on a page or partial view that utilize the jQuery Unobtrusive Validation that requires the user to input a note before submitting a form. However, upon running the page or partial view, the error message will always show or appear even without user interaction on page load.
@model Portal.Models.JobTicketNote

@{
    Layout = "";
}

<script src="~/Scripts/jquery.validate.js"></script>
<script src="~/Scripts/jquery.validate.unobtrusive.js"></script>

@using (Ajax.BeginForm("ManageJobTicketNote", "GGSDashboard",
   new AjaxOptions
   {
       InsertionMode = InsertionMode.Replace,
       UpdateTargetId = "JobTicketNotesTable"
   }, new { @id = "frmManageJobTicket" }))

{
    @Html.AntiForgeryToken()
    @Html.HiddenFor(m => m.DataID)
    @Html.HiddenFor(m => m.ButtonActivity)

    if (Model.ButtonActivity.Equals("Edit", StringComparison.OrdinalIgnoreCase))
    {
        @Html.HiddenFor(m => m.RowID)
        @Html.HiddenFor(m => m.TableID)
    }

    <div class="modal-header">
        <button type="button" class="close" data-dismiss="modal">&times;</button>
		<h4>Add New Note</h4>
    </div>
    <div class="modal-body">
        <div class="form-horizontal">
            @Html.ValidationSummary(true, "", new { @class = "text-danger" })
            <div class="form-group">
                @Html.LabelFor(model => model.Notes, htmlAttributes: new { @class = "control-label col-md-2" })
                <div class="col-md-8">
                    @Html.TextAreaFor(model => model.Notes, new { @class = "form-control", @rows = 7, @maxLength = "2000" })
                    @Html.ValidationMessageFor(model => model.Notes, "", new { @class = "text-danger" })
                </div>
                <div class="col-md-2"></div>
            </div>
        </div>
    </div>
    <div class="modal-footer">
        <input id="btnSave" type="submit" value="Save" class="btn btn-primary" />
        <button type="button" class="btn btn-default" data-dismiss="modal">Close</button>
    </div>
}
The current JavaScript code will get the value from the parameter and store it in a model object which will be converted to JSON string and then pass it to the controller action
function OpenNewJobTicketModal(DataID) {
    var manageType = 'New';
    var model = {
        DataID: DataID,
        ButtonActivity: manageType
    };

    $.ajax({
        type: 'POST',
        data: JSON.stringify(model),
        url: urlNewJobTicketNote,
        contentType: "application/json",
        success: function (result) {
            $('#modal-edit-TicketContent').html(result);
            $('#modal-editTicket').modal('show');
        },
        error: function (er) {
            OpenJQueryModal('Open New Job Ticket Note Form', er, 325, 150);
        }
    });
}
The existing controller action with an HttpPost request attribute has a parameter which is a model object that receives the value from the ajax call and pass it to the partial view's model.
[Authorize]
[HttpPost]
public PartialViewResult NewJobTicketNote(GGSJobTicketNote model)
{
	 GGSJobTicketNote tempModel;

	 tempModel = new GGSJobTicketNote();

	 tempModel.DataID = model.DataID;
	 tempModel.ButtonActivity = model.ButtonActivity;

	 return PartialView("../GGSDashboard/JobTicketManageNote", tempModel);
}
As you can see,the error message always appear on the form given the codes above.
@Html.ValidationMessageFor Will Always Show Or Display Error Message On Page Load In ASP.NET MVC
After doing some few changes to the codes, I manage to solve it by just passing the variable to the controller action instead of the model object. So the revised ajax call will only pass the variable converted to JSON string instead of a model object.
function OpenNewJobTicketModal(DataID) {
    $.ajax({
        type: 'POST',
        data: JSON.stringify({ DataID: DataID }),
        url: urlNewJobTicketNote,
        contentType: "application/json",
        success: function (result) {
            $('#modal-edit-TicketContent').html(result);
            $('#modal-editTicket').modal('show');
        },
        error: function (er) {
            OpenJQueryModal('Open New Job Ticket Note Form', er, 325, 150);
        }
    });
}
The controller action's parameter is also changed from model object to a string variable. After that, the error message disappeared on page load.
[Authorize]
[HttpPost]
public PartialViewResult NewJobTicketNote(string DataID)
{
	 GGSJobTicketNote tempModel;

	 tempModel = new GGSJobTicketNote();
	 tempModel.DataID = Guid.Parse(DataID);
	 tempModel.ButtonActivity = "New";

	 return PartialView("../GGSDashboard/JobTicketManageNote", tempModel);
}
Output
@Html.ValidationMessageFor Will Always Show Or Display Error Message On Page Load In ASP.NET MVC

Comments

Donate

Popular Posts From This Blog

WPF CRUD Application Using DataGrid, MVVM Pattern, Entity Framework, And C#.NET

TypeScript Error Or Bug: The term 'tsc' is not recognized as the name of a cmdlet, function, script file, or operable program.

Invalid nested tag div found, expected closing tag input