How do I pass data from javascript to a kendo window defined in asp mvc cshtml file? - kendo-ui

I have a kendo window defined in a cshtml file and opened from the client side via javascript. The window is meant to display error messages from validation checks done in javascript. Is there a way to pass a string to the window from javascript?
Here's the window definition in the cshtml file:
#(Html.Kendo().Window()
.Name("ErrorWindow")
.Title("INVALID")
.Content(#<text>
<div class="metro" style="height:136px; padding-left:30px; padding-top:20px">
<div style="padding:0px 20px 3px 0">
<div>
<p id="ErrorInfo">
</p>
</div>
</div>
<p style="padding-top:20px; padding-left:0px; padding-bottom:20px">
#(Html.Kendo().Button()
.Name("closeErrWndButton")
.HtmlAttributes(new { type = "button", #class = "k-primary", #style = "min-width:90px" })
.Tag("span")
.Content("OK")
.Events(ev => ev.Click("CloseErrorWindow"))
)
</p>
</div>
</text>)
.Modal(true)
.Resizable()
.Width(560)
.Visible(false)
)
Here's how it's opened in javascript:
var wnd = $("#ErrorWindow").data("kendoWindow");
wnd.center().open();
I'm hoping to do this completely client side if possible, ie. no ajax call.

It sounds like you want to raise a 'kendo-themed' message dialog box for the user to peruse.
Consider using the Kendo UI Dialog component. The examples state
Description
The Kendo UI Dialog is a modal popup that brings information to the user. It also provides actions through the action buttons to prompt the user for input or to ask for a decision. The component can also contain more complex UI elements that require the focus of the user. The Dialog widget is a subset of the Kendo UI Window widget where the most prominent difference is the added functionality for actions.
The example shows using an existing div as the basis of the dialog. You can however use a more sophisticated approach that will dynamically create, attach and destroy the dialog basis, all within a single closure function.

Related

Add and remove textbox at runtime in mvc3

In my page there is one textbox by default and one add button beside it. I need to add the another textbox when user click Add button. And there should be two buttons Add and Remove beside newly added text box. And same process goes on i.e., user can add Textbox using Add button and remove it using remove button.
I am new to mvc 3 so i am confused how to proceed. Is there any way like placeholder in asp.net so that we can add control at runtime.
Any suggestion and idea will be helpful to me
MVC is a very "hands-off" framework compared to Web Forms, so you're free to add the new textboxes how you like. Note that "controls" don't exist in MVC.
Here's how I'd do it:
Model:
class MyModel {
public Boolean AddNewTextBox { get; set; }
public List<String> MultipleTextBoxes { get; set; } // this stores the values of the textboxes.
}
View (I prefer the Web Forms view engine, I'm not a fan of Razor):
<% for(int i=0;i<Model.MultipleTextBoxes.Count;i++) { %>
<%= Html.TextBoxFor( m => m.MultipleTextBoxes[i] ) /* this might look like magic to you... */ %>
<% } %>
<button type="submit" name="AddNewTextbox" value="true">Add New Textbox</button>
<button type="submit">Submit form</button>
Controller:
[HttpPost]
public ActionResult MyAction(MyModel model) {
if( model.AddNewTextBox ) model.MultipleTextBoxes.Add("Yet another");
else if( ModelState.IsValid ) {
// your regular processing
}
}
You can also add more textboxes with Javascript and it work perfectly fine. All that matters is the HTML input elements. There's no cryptic viewstate. MVC is stateless.
Note that because I used <button type="submit"> my example will not work reliably in Internet Explorer 6-8 (sucks, I know), but you can replace them with <input type="submit"> with no ill-effects.
This requires some Javascript/JQuery... The following is a sketch only, but will hopefully be useful as a general approach.
The remove button
You want to render a button that can target its own container for removal. To do that, use some markup like this:
<div class="item-container">
<input type="button" onclick="removeItem(this)" />
</div>
And the Javascript for removeItem:
<script>
function removeItem(element) {
// get the parent element with class "item-container" and remove it from the DOM
$(element).find(".item-container").remove();
}
</script>
The add button
You could either use a partial view with Ajax, or use straight Javascript; which one is best likely depends on whether you need a round-trip to the server to create a new item. Let's say you need to go the the server to generate a new ID or something.
First, create a partial view and corresponding controller action; this should contain the remove button as above, as well as the text box and add button.
Now, create an Ajax form on your main page that gets invoked when you click Add:
<script src="#Url.Content("~/Scripts/jquery.unobtrusive-ajax.min.js")" type="text/javascript"></script>
#using (Ajax.BeginForm("New", new AjaxOptions() { UpdateTargetId="ajaxTarget", HttpMethod = "GET" })) {
<input type='submit' value='Add New' />
}
<div id="ajaxTarget"></div>
This code fetches your partial view (from the action New in the current controller) and adds the result to the ajaxTarget element.
Note The Ajax form requires Unobtrusive Ajax, which you can install via Nuget: Install-Package JQuery.Ajax.Unobtrusive.

MVC 3 unobtrusive validation - conditionally disable/enable validation

I have a form that has an option to enter dimensions for:
Width & Height
Width
Height
And I have two container divs that I hide/show depending on which of the three options is selected:
<div class="editor-field" id="width-container">
#Html.EditorFor(model => model.Width)
#Html.ValidationMessageFor(model => model.Width)
</div>
<div class="editor-field" id="height-container">
#Html.EditorFor(model => model.Height)
#Html.ValidationMessageFor(model => model.Height)
</div>
If height is selected, then width is not displayed on the form, how can I disable the unobtrusive validation on the Width input field in a fashion that will allow me to easily re-instate it if the user changes their mind i.e. removing data-* attributes is not an option. I'm happy to create an CustomAttribute class to handle this BUT I do not want to have to hack the standard jquery files to make this work as it makes updating to new versions a headache down the track. If all else fails I'll use my usual trick of adding a value of 0 to the fields when they are not visible and then removing it when they are shown.
EDIT:
Please be mindful that when Width is not visible it is not a "hidden" field per se it's just a input tag that's not visible to the user because the parent div has a style of display:none
You can set up the jQuery validator that's processing your unobtrusive validation to ignore hidden elements:
jQuery.validator.defaults.ignore = ":hidden";
// the line above is outside any $(document).ready(...) or similar
$(document).ready(function(){
...
});
...
So it seems that this is the answer to my question (I went hunting again on Google hard to search for things that didn't relate to "hidden" fields):
https://stackoverflow.com/a/7673985/491950
e.g.
$("#height-container input[type='text']").attr("disabled", "disabled");
Thanks for your answers.

Is it possible to load a partial view by selecting a Radio Button in mvc3

Can i use radio button's to select two different partial view, Without using Jquery?
yes and no. a partial can only be loaded (after initial page load) via ajax, so a partial page refresh isn't possible without using ajax. however, you could submit the selected radio button (via javascript) to the controller action and then determine inside the controller which radio button had been selected. It would then just be a case of selecting the appropriate view.
As I said, you can't go down the partial route without ajax in the mix, so the answer is no. also, you'd still have to use javascript in order to use the radio button in the submit, in which case, an ajax solution might be worth thinking about.
[edit] with deference to Splash-X, here's a quick work up of the hidden div scenario:
#*use either #Html.RenderPartial() or #Html.RenderAction() as required*#
<div id="developerDiv" style="display: none">
This is the developer stuff, in reality,
this would be populated as such #*#Html.RenderPartial("DeveloperPartial")*#
</div>
<div id="testerDiv" style="display: none">
And here we have the testers, again,
this would be populated as such #*#Html.RenderPartial("TestersPartial")*#
</div>
<div>
Developer :#Html.RadioButton("team", "developer", new { onclick = "showResult(this)"})
Tester :#Html.RadioButton("team", "tester", new { onclick = "showResult(this)"})
</div>
<div id="partialContainer"></div>
<script type="text/javascript">
function showResult(radio) {
var selected = radio.value;
if (selected == "developer")
document.getElementById("partialContainer").innerHTML
= document.getElementById("developerDiv").innerHTML;
else if (selected == "tester")
document.getElementById("partialContainer").innerHTML
= document.getElementById("testerDiv").innerHTML;
}
</script>
enjoy..

multiple button click in asp.net MVC 3

I am having multiple dynamic buttons on my asp.net mvc 3 page. what is the best way to handle button click in asp.net mvc 3? there is no event handling in asp.net, so what is the best practice to hadle.?
You could handle the buttons clicks using javascript by subscribing to their click event. For example with jQuery you could give those buttons a class and then:
$(function() {
$('.someClass').click(function() {
// a button was clicked, this will point to the actual button
});
});
or if those are submit buttons of a form you could give them the same name and different values and then on the server test the value of the name parameter. It's value will equal to the button that was clicked.
Let's suppose for example that you have the following form with multiple submit buttons:
#using (Html.BeginForm())
{
... some input fields
<button type="submit" name="Button" value="delete">Delete data</button>
<button type="submit" name="Button" value="save">Save data</button>
}
Now inside the controller action you are posting to you could determine which button was clicked:
[HttpPost]
public ActionResult Index(MyViewModel model)
{
var button = Request["button"];
if (button == "save")
{
// the save button was clicked
}
else if (button == "delete")
{
// the delete button was clicked
}
...
}
If the buttons do not require the same form data, then you can create two forms with different action methods. This is the easiest solution.
If you need to use the same form data, then there are a number of methods, inclduing Darin and tvanfosson's approaches. There is also an approach based on attributes that will select the correct action method based on which button is clicked.
http://www.dotnetcurry.com/ShowArticle.aspx?ID=724
Depends on what the buttons are doing. If they are logically separate actions, then you could have each postback to a separate action on the server side. This often also works they are variants of the same action, Save vs. Cancel, for instance where Save posts back the form and Cancel redirects to you the previous url (say, going back to details from edit). If the buttons represent different data that would get posted back to the same action, you can give them different values. If the buttons are named, the values will get posted back along with the rest of the form, assuming they are included in the form. If posting back from AJAX, you might need to explicitly serialize the button value along with the form.
Example of Save/Cancel
#using (Html.BeginForm())
{
//...
<button type="submit" class="submit-button button">Save</button>
#Html.ActionLink( "Cancel", "details", new { ID = Model.ID }, new { #class = "cancel-button button" } )
}
Then use CSS, perhaps in conjunction with jQuery UI to style the buttons.
<script type="text/javascript">
$(function() {
$('.button').button();
...
});
</script>

Toggle validation in MVC 3 Razor

I'm using MVC 3 with razor as the view engine and the unobtrusive client validation enabled.
I'm trying to create a form where the user has a radio button group to select their preferred contact method - either phone or email. Depending on the option selected, I want to show the appropriate textbox, but then also enable/disable the required validator for the appropriate textbox.
My markup looks something like this at the moment (Just starting out with MVC so please point out any obvious mistakes):
<div id="prefferedContact">
<p>Preferred Contact Method *</p>
<input type="radio" id="contactMethodEmail" name="PreferredContactMethod" value="email" #if (Model.PreferredContactMethod != "phone"){<text>checked="checked"</text>} /> <label for="contactMethodEmail">by email</label>
<input type="radio" id="contactMethodPhone" name="PreferredContactMethod" value="phone" #if (Model.PreferredContactMethod == "phone"){<text>checked="checked"</text>} /> <label for="contactMethodPhone">by phone</label>
</div>
<div id="contactMethodDetails" class="formItem">
<div id="emailAddressBox">
#Html.LabelFor(x => x.Email, "Email address")
#Html.TextBoxFor(x => x.Email, new { #class = "textbox" })
</div>
<div id="phoneNumberBox">
#Html.LabelFor(x => x.PhoneNumber, "Phone number")
#Html.TextBoxFor(x => x.PhoneNumber, new { #class = "textbox" })
</div>
</div>
</div>
</div>
There's some jquery function that adds an onclick event to the radio buttons to toggle between the two boxes depending on the selected value.
The Model - for these specific fields - doesn't have any required validation on it at the moment but is binding fine. Also, validation is working on other fields as expected
I really just need to get an idea of:
(a) is it possible to toggle validation on and off
(b) does this impact the ModelState validation in anyway (or do I need to customise it)
I had also thought of having the one textbox for the contact data, but I wanted to have regular expression validation for the email and for the phone number separately. If I was to have a single textbox, could I switch the validation rules on the textbox depending on the selected option???
Hope that's clear enough with enough information.
Thanks
Joel
You can perform class-level validation if you need to enforce rules based on multiple properties:
http://weblogs.asp.net/scottgu/archive/2010/12/10/class-level-model-validation-with-ef-code-first-and-asp-net-mvc-3.aspx
Unfortunately, this seems to only work server-side, so you'd have to implement custom client-side validation.
Another option would be to have two different models, one for each scenario (with common properties in a base class), but this might be a little more complicated.

Resources