MVC 3.0 : why no client-side validation messages? - asp.net-mvc-3

I have a model like this
public class SampleModel{
public int No{get;set;}
}
and in view I have a custom ValidationFor which shows a star near the inputbox for this field :
#Html.EditorFor(model => model.No)
#Html.ValidationMessageWithStarFor(model => model.No)
So in rendering I have a "*" nears the inputbox which tells the field is required. It works in server-side properly but it doesn't work in client-side.
In spite of Enabling ClientValidation in web.confing through these lines :
<add key="ClientValidationEnabled" value="true" />
<add key="UnobtrusiveJavaScriptEnabled" value="false" />
...how can I enable it?

You probably forgot to reference the following scripts in your page in addition to jQuery:
<script src="#Url.Content("~/Scripts/jquery.validate.js")" type="text/javascript"></script>
<script src="#Url.Content("~/Scripts/jquery.validate.unobtrusive.js")" type="text/javascript"></script>

the problem was because of the following code :
DataAnnotationsModelValidatorProvider.AddImplicitRequiredAttributeForValueTypes = false;
which prevents dataannotation to validate not nullable types.

Related

Load partial view with ajax actionlink

I've been trying to load a partial view but when clicking the link it inserts the whole site instead of just the partial view. What am I doing wrong?
In my template I have:
#Ajax.ActionLink("View list",
"List",
"SwitchView",
new AjaxOptions()
{
UpdateTargetId = "testajax",
InsertionMode = InsertionMode.Replace,
HttpMethod = "GET"
})
<div id="testajax"></div>
#section Scripts {
<script src="#Url.Content("~/Assets/framework/js/unobtrusive-ajax/jquery.unobtrusive-ajax.min.js")" type="text/javascript"></script>
}
My controller:
public class SwitchViewController : Controller
{
public PartialViewResult List()
{
return PartialView("~/Views/Partials/kund.unikum.se/_ListView");
}
}
I've also added these settings in web.config since they were missing:
<add key="ClientValidationEnabled" value="true"/>
<add key="UnobtrusiveJavaScriptEnabled" value="true" />
Also, when looking at the generated html link it's missing a "href" value?
<a data-ajax="true" data-ajax-method="GET" data-ajax-mode="replace" data-ajax-update="#testajax" href="">View list</a>
Screenshot of the loaded resources and the view
Have you set Layout=null in the partial view? if not then set and check. let me know if you still facing the issue.

Struts2 AJAX validation doesn't stay on page

I've been trying for a few days now to make Struts2 AJAX validation work but I can't solve one last problem. I'm using the struts2jquery plugin to asynchronously submit my form:
<div id="result"></div>
<s:form action="RegisterUser" theme="xhtml" method="post">
<s:textfield key="firstname" label="First name" size="35"
required="true" />
<s:textfield key="lastname" label="Last name" size="35"
required="true" />
<s:textfield key="address" label="Address" size="35"
required="true" />
<s:textfield key="phone" label="Phone number" size="35" />
<s:textfield key="username" label="Username" size="35"
required="true" />
<s:password key="password" label="Password" size="35"
required="true" />
<s:textfield key="email" label="E-mail address" size="35"
required="true" />
<sj:submit key="Inregistrare" targets="result" align="right"
button="true" validate="true" onSuccessTopics="notifyRegistration" />
</s:form>
I've included the required scripts:
<script type="text/javascript" src="./js/registerScript.js"></script>
<!-- This files are needed for AJAX Validation of XHTML Forms -->
<script src="${pageContext.request.contextPath}/struts/utils.js" type="text/javascript"></script>
<script src="${pageContext.request.contextPath}/struts/xhtml/validation.js"
type="text/javascript"></script>
and the tag:
<sj:head jqueryui="true" />
The onSuccess handler:
$(document).ready(function(){
$.subscribe('notifyRegistration', function(event,data) {
var registrationStatus = event.originalEvent.data.registrationStatus;
if(registrationStatus == 'SUCCESS'){
alert('Contul dumneavoastra a fost creat cu success!');
window.location.href = "./index.html";
} else {
alert('Contul dumneavoastra nu a putut fi creat. Va rugam incercati din nou.');
}
});
});
My configuration looks like this:
<action name="RegisterUser" class="actions.Register" method="execute">
<interceptor-ref name="jsonValidationWorkflowStack"/>
<result name="input">/pages/Register.jsp</result>
<result type="json"/>
</action>
And the execute method of my action class:
public String execute() throws Exception {
if (isInvalid(getUsername()) || isInvalid(getPassword())
|| isInvalid(getEmail())) {
registrationStatus = REGISTRATION_ERROR;
}
if (registerUser()) {
registrationStatus = REGISTRATION_SUCCESS;
return SUCCESS;
}else {
registrationStatus = REGISTRATION_ERROR;
}
return SUCCESS;
}
The registerUser() method makes the actual insert into the database. The validation XML is called Register-Validation.xml.
The validation works fine - if some fields are not filled in, it shows the error labels without refreshing the page. My problem is that even is the action returns SUCCESS or ERROR, the browser displays the JSON that it sent back on another page, ../Register.action. I have no idea why it doesn't enter my onSuccess handler. I've successfully used AJAX on other forms, the only difference here is that I use the validation xml and the jsonValidationWorkflowStack interceptor. Why is this happening and how can I avoid being redirected? Why doesn't the request reach the onSuccess handler?
Do you have getters for registrationStatus in your Action ?
I would put an alert(event.originalEvent.data.registrationStatus); in your notifyRegistration callback function, just to see what is its value.
By the way, it seems that you have mixed
Struts2-jQuery Plugin AJAX Form Validation with Struts2 XHTML Theme
with
Struts2-jQuery Plugin: Remote Link that handle an JSON Result with an onSuccessTopic
AFAIK (but I've never used this specific kind of validation), the validation should not be handled in execute(), but in validate() or through XML, or with Annotations.
The example in Struts2-jQuery Plugin showcase uses Annotations, but you can easily transform it in XML and try the showcase.
You would have no need to use the javascript function nor the onSuccessTopic at all, following the example.
You can run it in the showcase too, under Forms -> Forms with Validation (but stick to the documentation for the code, because the code in the showcase seems to miss some pieces... for example the validation against "test" password).

Client Side Validation Not Working With Foreign Keys

Client side validation is not working for me for foreign keys only.
I have
<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>
included as well as
<add key="ClientValidationEnabled" value="true" />
<add key="UnobtrusiveJavaScriptEnabled" value="true" />
set in my web.config file.
There are no custom attributes or anything. It's something as simple as
[Required(ErrorMessage = "Fiscal year is required")]
[Display(Name = "Fiscal Year")]
public int FiscalYearId { get; set; }
Any ideas on this? I've searched for a solution, but all I have found are cases where it does not work at all and most solutions say to make sure the two above scripts are sourced and the two above keys are added to the web.conifg file.
I am getting no js errors and I have monitored with firebug. Everything appears to work perfectly, but it obviously is not.
Once I correct the non-foreign key fields and resubmit, data validations do work server side. This is an issue because it is creating a double validation and annoys the hell out of the users.
Help is much appreciated.
Below is the Html portion. It is contained in a using block. It's standard MVC3 generated CRUD code.
<div class="editor-label">
<label for="FiscalYearId">Fiscal Year</label>
</div>
<div class="editor-field">
<select id="FiscalYearId" name="FiscalYearId">
<option value="">---Select Fiscal Year---</option>
<option value="1">FY2013</option>
</select>
<span class="field-validation-valid" data-valmsg-for="FiscalYearId" data-valmsg-replace="true"></span>
</div>
I think there are no metadata attributes rendered in html. Try this in your view:
if (this.ViewContext.FormContext == null)
{
this.ViewContext.FormContext = new FormContext();
}

How to client side validate the dropdownlist box in razor mvc3?

How to client side validate the dropdownlist box.....
#Html.DropDownListFor(per => per.Gender, new[] {
new SelectListItem(){Text = "Male" , Value="Male"},
new SelectListItem(){Text ="Female" , Value = "Female"},
}, "Select Your Gender")
#Html.ValidationMessageFor(per => per.Gender)
Include jquery validate plugin scripts in your view along with jQuery (if not already refered in the Layout.cshtml)
#model SomeModel
<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>
#using (Html.BeginForm())
{
#Html.DropDownListFor(per => per.Gender, new[] {
new SelectListItem(){Text = "Male" , Value="Male"},
new SelectListItem(){Text ="Female" , Value = "Female"},
}, "Select Your Gender")
#Html.ValidationMessageFor(per => per.Gender)
<input type="submit" />
}
And make sure the SomeModel's Gender property is required
[Required]
public string Gender { set;get;}
Update your web.config to and set the AppSetting called ClientValidationEnabled to true
<appSettings>
<add key="ClientValidationEnabled" value="true" />
<add key="UnobtrusiveJavaScriptEnabled" value="true" />
</appSettings>
Now when you submit, it will execute the client side validation, if javascript is enabled in the browser.

Client-side validation breaks in IE because of PropertyProxyValidator and ScriptManager cooperation

The specific of the project is in using Enterpise Library for Server side validation and jQuery for client-side validation. So I have the next simple form for example:
<asp:Content ID="_mainContent" ContentPlaceHolderID="MainContent" runat="server">
<script src="../../../Scripts/jquery-1.3.2.js" type="text/javascript"></script>
<script src="../../../Scripts/jquery.validate.js" type="text/javascript"></script>
<script type="text/javascript">
$(document).ready(function() {
$("#aspnetForm").validate({
rules: {
"<%= _txtProjectName.UniqueID %>": {
required: true
}
}
});
});
</script>
<asp:TextBox ID="_txtProjectName" runat="server" CssClass="textBoxWithValidator_long" />
<entlib:PropertyProxyValidator id="_validatorProjectName" runat="server" ControlToValidate="_txtProjectName"
PropertyName="ProjectName" SourceTypeName="LabManagement.Project.Project" />
<asp:Button CssClass="cell_InlineElement" ID="_btnSave" runat="server" Text="Save" onclick="_btnSave_Click"
Width="50px" />
<asp:ScriptManager ID="ScriptManager1" runat="server" EnablePageMethods="true">
</asp:ScriptManager>
</asp:Content>
The problem is in the next: client-side validation worked correctly before I needed to implement some AJAX.NET feature. So I have to add to the page ScriptManager (the last two lines in the code). But after that the next situation appeared:
In InternetExplorer((7) - only in IE !!! - in Firefox everything works correctly) after clicking save button, if left the textbox ProjectName empty the client-side jquery validation appears but (!) the page submits to the server anyway.
Some notes:
If delete PropertyProxyValidator from the page - the client-side validation works correctly in IE but I need it for specific of the project.
It seems that the problem is in the function WebForm_OnSubmit() that is inserted to the form after PropertyProxyValidator adding. ( ... <form name="aspnetForm" method="post" action="Project.aspx?TransType=NewProject" onsubmit="javascript:return WebForm_OnSubmit();" ...>)
Could anyone help, please.
Just in case someone else comes across this issue, upgrade jQuery to 1.4.2. This will fix this bug.

Resources