Getting client side validation to work with Telerik MVC Window - asp.net-mvc

I am using a telerik mvc window extension that is triggered from a custom template link in a telerik mvc grid. The window is modal and it contains a form for editing data. After successfully implementing client side validation using a standard html page, I have been trying to implement it in the telerik mvc window. I have not been able to do so successfully. Is this possible? Does anybody have a working example of this?
Thanks
Ozzy

You need to load to page in an IFrame. To do this, make sure the url in LoadContentFrom method starts with http or https:
<%= Html.Telerik().Window()
.Name("Window")
.LoadContentFrom("http://www.example.com")
%>
if you're using the Url.Action() helper to get the url, include the protocol parameter to get the full url.
E.g
Url.Action("action name","controler name", "http") <--may also need to include route values or null route value dictionary.
To close to window, you'll need to make a call back to the parent view, try this:
add a bool isValid property to your model
if succesfully validated, reload the view with isValid equals true
onload:
var isValid = '<%: Model.IsValid%>';
if(isValid == 'True')
{
window.parent.$('#MyWindow').data('tWindow').close();
}

It is possible. First make sure you have your ViewModel property that needs validation decorated with the appropriate attribute. Eg: [Required(ErrorMessage = "this is required")]
Then include all the client validation scripts found in telerik's folder in your application.
<script src="../../Scripts/jquery.validate.min.js" type="text/javascript"></script>
Make sure you use the latest build of teleriks extensions. hth.

Related

Pass javascript parameter to partial view in asp.net mvc

lets say I want to a partial view like the following sample
#Html.RenderAction("ListDocuments", "MultiFileAttachments", new { id = jsparameter });
in the jsparameter I want to pass as a parameter that is the result of a javascript function. Maybe this is not logical because javascript runs on the client, but how can I achieve a similar functionality ? thank you in advance
If you need to call a part of a page based on some actions or values determined by actions on the client side, then you should think to use JavaScript (preferably jQuery) and Ajax.
Through jQuery-Ajax, you could easily call a Partial view through the Contoler and since it's a regular HTTP request, you would be able to pass all the parameters you need.
Using code as :
#Html.RenderAction("ListDocuments", "MultiFileAttachments", new { id = jsparameter });
is not possible since it is rendered by the server before it's sent to the client browser.

ASP.Net Web Api + KnockoutJs + MVC4 - Tying it together

I am starting a new project, and keen to make use of the KnockoutJS + Web Api which are new to me, I have a good understanding of the Web Api, but Knockout is tough to get my head around at the moment.
This is my initial thoughts of how I want my app to work:
I have a standard MVC controller such as LeadsController
LeadsController has an Action called ListLeads, this doesn't actually return any data though, but just returns a view with a template to display data from Knockout.
The ListLeads view calls my api controller LeadsApiController via ajax to get a list of leads to display
The leads data is then mapped to a KnockoutJs ViewModel (I don't want to replicate my view models from server side into JavaScript view models)
I want to use external JavaScript files as much as possible rather than bloating my HTML page full of JavaScript.
I have seen lots of examples but most of them return some initial data on the first page load, rather than via an ajax call.
So my question is, how would create my JavaScript viewModel for Knockout when retrieved from ajax, where the ajax url is created using Url.Content().
Also, what if I need additional computed values on this ViewModel, how would I extend the mapped view model from server side.
If I haven't explained myself well, please let me know what your not sure of and I'll try and update my question to be more explicit.
I think your design is a good idea. In fact, I am developing an application using exactly this design right now!
You don't have to embed the initial data in your page. Instead, when your page loads, create an empty view model, call ko.applyBindings, then start an AJAX call which will populate the view model when it completes:
$(function () {
var viewModel = {
leads: ko.observableArray([]) // empty array for now
};
ko.applyBindings(viewModel);
$.getJSON("/api/Leads", function (data) {
var newLeads = ko.mapping.fromJS(data)(); // convert to view model objects
viewModel.leads(newLeads); // replace the empty array with a populated one
});
});
You'll want to put a "Loading" message somewhere on your page until the AJAX call completes.
To generate the "/api/Leads" URL, use Url.RouteUrl:
<script>
var apiUrl = '#Url.RouteUrl("DefaultApi", new { httproute = "", controller = "Leads" })';
</script>
(That's assuming your API route configured in Global.asax or App_Start\RouteConfig.cs is named "DefaultApi".)
The knockout mapping plugin is used above to convert the AJAX JSON result into a knockout view model. By default, the generated view model will have one observable property for each property in the JSON. To customise this, such as to add additional computed properties, use the knockout mapping plugin's "create" callback.
After getting this far in my application, I found I wanted more meta-data from the server-side view models available to the client-side code, such as which properties are required, and what validations are on each property. In the knockout mapping "create" callbacks, I wanted this information in order to automatically generate additional properties and computed observables in the view models. So, on the server side, I used some MVC framework classes and reflection to inspect the view models and generate some meta-data as JavaScript which gets embeded into the relevant views. On the client side, I have external JavaScript files which hook up the knockout mapping callbacks and generate view models according the meta-data provided in the page. My advice is to start out by writing the knockout view model customisations and other JavaScript by hand in each view, then as you refactor, move generic JavaScript functions out into external files. Each view should end up with only the minimal JavaScript that is specific to that view, at which point you can consider writing some C# to generate that JavaScript from your server-side view model annotations.
For the url issue add this in your _Layout.cshtml in a place where it is before the files that will use it:
<script>
window._appRootUrl = '#Url.Content("~/")';
</script>
Then you can use the window._appRootUrl to compose urls with string concatenation or with the help of a javascript library like URI.js.
As for the additional computed values, you may want to use a knockout computed observable. If that is not possible or you prefer to do it in .Net you should be able to create a property with a getter only, but this won't update when you update other properties on the client if it depends on them.

Simple Validation for a Single Text Box in ASP.NET MVC

I have added a text box to a simple form in ASP.NET MVC and I want a client-side 'required' validation for this.
I know I can do this using a strongly typed model view but I would like to do it manually in this case. Is there a simple way to perform this?
I tried setting the Model/property name of the Html.ValidationMessage helper to the input name but this didnt work:
#Html.TextBox("emailStr" )
#Html.ValidationMessage("emailStr","* Required")
Assuming you use default jQuery validation plugin, you can use Rules.Add method on client side for this
$("#emailStr").rules("add", {
required: true,
messages: {
required: "* Required",
}
});
Also, do not forget to include jquery.validate.min.js
Not sure why you would want to do it manually - but I don't think you can use #Html.ValidationMessage unless you use a TextBoxFor. You can't use the TextBoxFor unless you have a model to work with inside the view.
You could write some javascript/jquery to find the textbox and make sure it's not empty, and if it is, unhide an element with the validation message in it.

Required Attribute for bool value type when used as checkbox

I'm running into a problem where I have a simple add/edit form and using client-side validation (jQuery/MicrosoftMvcJQueryValidation.js) which is generated from data annotations and enabled client side by calling the following in my view:
<% Html.EnableClientValidation(); %>
This seems to work fine for most elements, however I have an instance where I have a boolean property which is rendered as a checkbox using:
<%= Html.EditorFor(model => model.Chargeable)%>
Which can be either true/false (ticked/unticked).
As the bool is a value type, and not nullable, it is being rendered as a required property and displays an error (client side) when the form is submitted reading "The Chargeable field is required.", however, as the HTML that is generated is two part (both checkbox and hidden value) it will pass the post back validation.
After browsing the MVC 2 source code, I've managed to put a "quick and dirty" fix in for the moment, which is to set:
DataAnnotationsModelValidatorProvider.AddImplicitRequiredAttributeForValueTypes = false;
Any one else got any ideas or suggestions on how I can get around this?
IMO, I dont think MVC should be setting the client-side required validator for checkboxes rendered using the Html.EditorFor/Html.CheckBox(For) methods.
Note: I'm using the ASP.NET MVC 2 RC2 and the MicrosoftMvcJQueryValidation.js from the matching MVC Futures release.
I suppose the easiest way of handling it is to call the rules("remove", [rules]) function on the elements (mainly checkboxes) that I want to remove the client-side validation from:
<script type="text/javascript">
$(document).ready(function() {
$('#Chargeable').rules('remove', 'required');
});
</script>

How can I use Html.ValidationSummary with Ajax.BeginForm?

I have an AJAX form that I am creating in my MVC project. If the form is submitted using normal browser function and a page refresh occurs I get validation information rendered in the form (the built in MVC validation based on ViewData.ModelState).
Is there a similiar validation mechanism for AJAX forms?
<% using (Ajax.BeginForm("Create", "GraphAdministration", new AjaxOptions()
{
OnSuccess = "newGraphSuccess",
OnFailure = "newGraphFailure",
HttpMethod = "POST"
}))
{ %>
<!-- some form stuff in here !-->
<% } //end form %>
It really depends on where you are getting the content from to display once the form has been posted. The Validation summary is performed created on the server so that is where you have to do the work.
As an example I was using some partial content in an .ascx file to render a form. You get the form in the page the first time round by calling the action directly with Html.RenderAction
You would have your Ajax.BeginForm etc. in the .ascx file. Then call it directly in an action.
When the Ajax call is made from the browser you get it to post to the same action. That way you can do all of the server side validation that you would normally. You should set up the Ajax call to replace the original form with the new html that is returned by the action.
One thing that you have to be aware of is that the replace JavaScript will replace the content of an element not the element itself so remember to us the id of a surrounding element.
Apologies if that is a little convoluted, if you want more details just comment and I'll flesh out the relevant bits.
Extra Detail:
All of this assumes that you are doing all of the validation on the server.
You are going to have a View that has all of the page stuff in it and then some partial content in a .ascx file, this is where your ajax form lives, it needs to be set to replace content by id. Its easiest if it has the same name as the action your ajax is going to call.
You can use Html.RenderAction to get it into the View. You can also pass in data with other versions of the same method. Your essentially calling it in the same way your ajax code will.
You will need to wrap it all in a div with an id set. Use this id in the partial as the content to replace.
When you render the page the html for the form and all of the ajax stuff will get put in.
When the ajax action is called the partial content will be returned with any validation performed. It will replace the content of the div that you gave the id to.
You can have different versions of the action by using [AcceptVerbs(HttpVerbs.Get)] and [AcceptVerbs(HttpVerbs.Post)] attributes
The main problem with this method is that its not self contained, the div with the id is external to the partial.

Resources