I have an asp.net user control which is plugged into both asp.net and MVC pages
When the control is on an asp.net page the client validation in it works fine but when the control is on an MVC page the following call in the js validation fails;
Page_ClientValidate('ValidationGroup');
with the error in Chrome: Object [object global] has no method 'Page_ClientValidate'
How can I get my client side validation to work on my mvc pages when the hyperlink button is clicked?
I need whatever the solution is to work across both MVC and ASP.Net as our site is a combination of the two
Try something like this,
$('#Form').submit(function () {
if (typeof (Page_ClientValidate) == 'function') {
Page_ClientValidate();
if (Page_IsValid == true) {
alert('the form is valid');
}
} else {
if ($(this).valid()) {
alert('the form is valid');
}
}
});
What Kind of validations are you trying to do?
first option:
MVC gives you great tool for validations:
Have you heard about "Data Annotations" tool?
as you configure your model fields you can use the common validation annotation called "required" for example:
Model:
[Required ("ID Field is Required")]
public int ID {get; set;}
View:
#html.texboxfor(m=>m.ID)
#validatefor((m=>m.ID)
and on the view you'll see a red message next the the input field you're trying to validate.
you can change the default messages design and location using CSS.
There is a good Tutorial for that matter at:
http://www.asp.net/mvc/tutorials/mvc-music-store/mvc-music-store-part-6
there is more data annotation validations, it depends on what kind of validations are you trying to do..
Second option:
you can use validate.js for input validations - it gives you the ability to validate almost any kinds of inputs - from numbers and strings to tables, and you can custom you own validation rules...
Default Option:
Build your Own Validation Method using native js for example:
if( $(.myClass).length<0 )
{
alert( "Please Insert Value" );
return false;
}
EDIT:
you can create :
View:
#using("actionMethod","controller")
{
<!--Content contains "names" of tags-->
<input type="submit"/>
}
OR
Controller:
When post back occurred , check the names and return to the same View, if the names are not satisfy.
end EDIT
If you have more questions, please ask.
Hope I Helped, Good luck.
Is there anyway to use an MVC Razor validation method on an ascx web forms user control that is being embedded in an MVC View using RenderPartial?
The problem I now have is that my ascx user control has a custom validation control on it (just the standard web forms custom validator) and when this control is used on an MVC View (by using Render Partial) the view errors with the following error;
Control 'ctl00_ProductListView_ctrl5_ctl00_ctl00_valValueMultiple' of type 'CustomValidator' must be placed inside a form tag with runat=server.
This is because the MVC view doesn't have a form on it obviously but I can't simply add one.
I cant'simply change this from an ascx web forms user control because it is dynamically added to both MVC and Web Forms pages (we have a mixed site of MVC and Web Forms - this is beyond my control) throughout our website.
Related
In asp.net web forms we have user controls as reusable components for pages. These user controls can be passed values externally through public properties e.g. on a web form we can drop this user control to display a text which came from db (like content managed system) by setting key as public property to this user control and it will pull the value. ( this key, value can be stored in application cache as list or dictionary to avoid DB round trips).
I want to implement same idea in asp.net mvc, but new to it. Any expert suggestion to implement same idea will be very helpful? Thanks
The concept of a user control is a PartialView; there are two ways to use a partial view. The first is to define a partial in the view itself:
#Html.Partial("NameOfViewInControllerFolder", ModelForPartialview)
The second way is have an action method that returns a partial view:
public ActionResult X()
{
return PartialView("NameOfView");
}
And from your view use:
#Html.Action("X", "ControllerName")
And that will call the action method, and insert the results. To ensure that action is only called within the a view, you can use the [ChildActionOnly] attribute.
If an action method, you can use JQuery to request it via AJAX, and load the results into a view:
$.ajax({
type: "GET|POST",
url: "#Url.Action("X", "ControllerName")",
success: function(d) { /* d is HTML */ });
I'm using silverlight content within a aspx page.i have created silverlight page is in a separate silverlight project and i have added that project to my normal asp.net application ClientBin.i need to redirect to a aspx page on my asp.net project from a silverlight page button click.how can i achive this?
I think you have one of two options. In your view model for that silverlight control, during the initialization, Bind the navigate URI for a hyperlink button to the desired URI you want to navigate to. Option 2 (a lot smoother): On the click method, Invoke a javascript method on the page that hosts the silverlight object. That method would then do some sort of smooth jquery transition or just a simple navigation for you.
Option 1: <HyperlinkButton NavigateUri="{Binding DesiredURL}" TargetName="_blank" />
For option 2, remember to include:
using System.Windows.Browser;
Option 2:
public void OnFancyNavigate(string _destination)
{
//call the browser method/jquery method (I used constants to centralize the names of the respective browser methods
try
{
HtmlWindow window = HtmlPage.Window;
window.Invoke(Constants.TBrowserMethods.BM_FANCYNAVIGATE, new object[] { _destination});
}
catch (Exception ex) { System.Diagnostics.Debug.WriteLine(ex.ToString()); }
}
Lastly, define the javascript method in the aspx/html/.js file that hosts the xap content:
function fancyNavigate(_destination) {
//some fancy jquery or just the traditional document.location change here
}
C# will locate the javascript method when invoked from your code, and you should be good to go
I have 4 forms in my asp.net mvc view. I have enabled client side validation on each by put <% Html.EnableClientValidation(); %> Above Html.BeginForm() of each form. The issue is that regardless of the fact that I've specified ID's for the forms the first form on the page gets validated whenever I click submit of the other forms.
Is this usage supported or am I doing something wrong?
this may help
<%=Html.ValidationMessageFor(m => ((RegistrationFormModel)m.Data).Email, null, new { id = "registration_Email" })%>
Make sure you have validation messages for the properties. Unless you have a validation message or (ValidateFor()), the property isn't added to the set of elements validated on form submission.
See this question for more info.
MVC2 fully supports the setup that you're looking for, my guess is that you're applying this to something like displaying a registration form and a login form on the same page?
If so you just need each form to have independent property names, i.e.
LoginModel would have a Username property and RegistrationModel would have a RegistrationUsername.
Not a great example there, but what's probably happening is that the validation is firing cross form because your properties have the same name.
I do not like to use the calendar from .NET, so I would like to have one Web User Control with 3 drop down boxes, day, month, year. [CODE DONE].
I want to be able to call this Control and initialize it with start year and end year, and with or without selected date.[CODE DONE].
This control will see if there is one valid date selected and return bool [CODE DONE].
Then in my web page I would like to able to see if that web user control is valid, in a way that I can use with the normal .NET validation (associate one required field), the problem is that I don't know where to put this code and retrieve it to the validation control on the web page. [CODE NOT DONE].
How can I do this?
There are two steps to integrating your custom server controls with the validation framework.
(1) Server side: you'll need to add a ValidationPropertyAttribute to your class, so the validation framwework knows what to look at when validating:
[ValidationProperty("SelectedDate")]
public class MyDateControl : WebControl
{
public DateTime? SelectedDate { get { ... } set { ... } }
}
(2) To hook up with client side validation, you have to make sure there's an input tag associated with your control. One way of doing that is rendering an <input type="hidden"> as the first child tag of your web control's HTML. The validation framework will pick up on that. The remaining thing to do here, is to set this hidden field through JavaScript each time your one drop downs changes.
This way, you can tie in with the existing validation controls. If you want different way to validate, you should look at a CustomValidator.
You want to use the CustomValidator control for this. See this tutorial that explains how to implement it with both a client-side and server-side version of the validation.
I am using jQuery and jQuery.validate plugin to validate ASP.NET pages, since I found jQuery Validation plugin better than ASP.NET validation controls.
I have used This validation code for Login and simultaneously for other pages like register and many others.
//.NET code
Dim jsValidate As String = String.Format("Validators.validateLogin('{0}','{1}');", _
txtUsername.ClientID, txtPassword.ClientID)
btnLogin.Attributes.Add("onclick", jsValidate)
//javascript code
Validators.validateLogin = function(txtUsername, txtPassword) {
$('#aspnetForm').validate();
$('#'+txtUsername).rules('add', {
required: true
});
$('#'+txtUsername).rules('add', {
required: true
});
}
Now the problem I am facing is if I have multiple controls on a page which require or not require validation. How to handle that situation. Bcoz once someone clicked on Login button it starts validation function and on pressing on some other button in some other control, it stuck with current validation. I wish if jQuery validation plugin can handle some groups like ASP.NET validationGroup, it could be a lot easier. Anyone have suggestions?
Thanks in Advance
You might try overloading CSS classes as validation groups. Basically you could filter out the controls whose class didn't match a specific pattern and only validate against those. Kind of a hack but it might just work for you.