Radio button selection event in MVC - asp.net-mvc

I am a beginer ...I don't know how to write code during the radio button select change in MVC....I have used it like this
In csHTML page
#Html.RadioButtonFor(model=>Sales.Pay_Mode, true)Cheque
#Html.RadioButtonFor(model=>Sales.Pay_Mode, false)Cas
This is my cs page code....Where i want write the change event code and how i get the selected value in control page.My requirement is during radio button change i want change the style of the textbox enable as false..
#Html.TextBox("ChequeNo")

Considering the information that you have provided in your question, the following code would fulfill your expectation
#Html.RadioButtonFor(model => model.PayMode, "Cheque") Cheque
#Html.RadioButtonFor(model => model.PayMode, "Cas") Cas
#Html.TextBox("ChequeNo", null, new {id="theTextBox"})
<script type="text/javascript">
$("input[name='PayMode']").change(function () {
var selectedRadio = $("input[name='PayMode']:checked").val();
if (selectedRadio == 'Cas') {
$("#theTextBox").attr("disabled", "disabled");
} else {
$("#theTextBox").removeAttr("disabled");
}
});
</script>

The is no control events handler in MVC like in WebForms or something like this. You must use javascript code to implement your logic. For example with jQuery
$('.your-radio-class').change(function(){
$('#your-textbox-id').css('margin-left', '100px')
});

Related

Kendo validator not working on text change

I am using kendo controls for my project. I was using jquery validation to validate my controls at client side but as jquery validation is not working for kendo controls so I am using kendo validators to validate the controls.
I am using dataannotation validation with MVC 5 project. Here is sample dojo.
It is working perfect but the validation only appear on focus-out or blur event. Is there any way to validate control on change of value of control like jquery validation?
Update:
Here is the complete solution that helped me to resolve this issue:
if ($.validator !== undefined) {
$.validator.setDefaults({
ignore: [],
highlight: function (element, errorClass) {
element = $(element);
var highLightElement;
if (element.parent().hasClass("k-picker-wrap") ||
element.parent().hasClass("k-numeric-wrap")) {
highLightElement = element.parent().parent();
}
else if (element.parent().hasClass("k-widget")) {
highLightElement = element.parent();
} else if (element.parent().children('.k-upload-empty').length > 0) {
highLightElement = $(element.parent().children('.k-upload-empty')[0]);
} else {
highLightElement = element;
}
highLightElement.addClass('input-validation-error');
},
unhighlight: function (element, errorClass) {
element = $(element);
var highLightElement;
if (element.parent().hasClass("k-picker-wrap")
|| element.parent().hasClass("k-numeric-wrap")) {
highLightElement = element.parent().parent();
}
else if (element.parent().hasClass("k-widget")) {
highLightElement = element.parent();
} else {
highLightElement = element;
}
highLightElement.removeClass('input-validation-error');
}
});
}
You have 2 ways to meat your purpose:
Using jQuery Unobtrusive Validation with KendoUI
Background
As you know the Kendo UI Editor creates a different elements than HTML form elements. Other JavaScript editors work in a similar fashion. The actual HTML is hidden using CSS (display: none;), and therein lies the issue. By default jQuery Validation ignores hidden input fields. There are validation data-* attributes on the form elements, but since it is hidden, when the unobtrusive validation fires, the editor is ignored.
Solution
You have 2 ways to solve this issue and perfectly work with both technologies. Read the Making the Kendo UI Editor Work With jQuery Validations and if you have any problem for implementing, please read Kendo UI NumericTextBox With jQuery Validation as an example for NumericTextBox
Then, You may have problem to assign proper CSS class in case of validation. You can read adding jquery validation to kendo ui elements.
Just using KendoUI Validators
You should implement desired event for the validation purpose. Here you need onChange event to work like jQuery Unobtrusive Validation. Use the following code as it describes what to do:
$(document).ready(function () {
function widgetChange() {
//place validation logic
};
$("#dropdownlist").kendoDropDownList({
dataTextField: "text",
dataValueField: "value",
dataSource: data,
change: widgetChange
});
})
You may want to use both of them! So take a look at .Net Mvc 3 Trigger (other than submit button) Unobtrusive Validation
Update
A dojo for implementing with last solution which added a pattern="\d+" to search input with a validation message. The validation is called by filtering event for the same input. Note that you should use desired event based on UI element, here we used filtering for autocomplete instead of using change for DropDownList.
I recently found a new implementation which is looking good to try and test. That is available at aspnet-mvc getting-started validation

jquerymobile datebox - How to call a function when date selected

I have inherited some code using the jquerymobile datebox. The code so far concentrates on making the application look correct. I need to make it work so that when a date is selected, the server is called with the date and a new page loaded. Most examples just change the date in the page.
The code so far is :-
$('#daycal').live('click', function() {
$('#catchdate').datebox('open');
});
$( "#catchdate" ).bind( "change", function(event, ui) {
$("#test1").val("xyz");
});
And
<div data-role="fieldcontain">
<label for="catchdate">Some Date</label>
<input name="catchdate" type="date" data-role="datebox" id="catchdate" data-options='{"mode":"calbox", "useNewStyle":true, "theme":true, "themeHeader":"f", "themeDateHigh":"f", "themeDatePick":"e", "themeDate":"f", "centerHoriz":true}' />
<input id="test1" type="text"/> <!-- Later changed to a function call -->
</div>
In my simple test I expected the text in the input to change when a date was selected.
I have seen an example using the bind to change event, but I cannot get it to work. In the example I was just changing the value in an input element, later this will be changed to a function call.
I also saw somewhere in my search for an answer, a comment that 'live' was deprecated.
Finally, I thought I could use closeCallback ('Callbacks ('openCallback' and 'closeCallback') are simple to work with...') but could not find any examples of how it should be used.
What changes do I need to make to obtain the functionality I need?
You could try using the close function of the date box, so that when user changes the date selection he makes and closes the date box you can call the server method with the selected date:
$('#DateSelectorId').bind('datebox', function (e, passed) {
if ( passed.method === 'close' ) {
// selected date
var date = $('#DateSelectorId').val();
// make your service method and change page to another page
}
});
think this can fix it
$('#catchdate').on('datebox', function(e, p) {
if ( p.method === 'close' ) {
alert('DO SOMETHING');
}
});
u can go and test it on Fiddle
**i think u need some validation check for input box empty or not

Kendo UI Grid in MVC with Conditional Custom Command Button

I have a KendoUI Grid I'm using an MVC web application, all working fine however I want to add a custom command button that is shown conditionally in the UI and simply executes a command on my controller passing it the required parameter.
columns.Command(command => command.Custom("UnlockAccount").SendDataKeys(true).Click())
The command is specified as above but I only want the button to show when the DataItems IsLocked property is true.
I also cannot figure out how to just call and method on the controller rather. I cannot find a demo of this on the Kendo site and not sure how to move this forward.
Here is a specific example for using client templates for conditional command buttons.
const string ShowUpdateButton = "#if (IsNetReversal == false) {#<a class='k-button k-button-icontext k-grid-edit' href='\\#'><span class='k-icon k-edit'></span>Update</a>#}#";
const string ShowReverseButton = "#if (IsNetReversal == false) {#<a class='k-button k-button-icontext k-grid-reverse' href='/JournalDetail/Reverse/#: ID #' ><span class='k-icon k-reverse'></span>Reverse</a>#}#";
const string ShowDeleteButton = "#if (IsAdjustment == true) {#<a class='k-button k-button-icontext k-grid-delete' href='\\#'><span class='k-icon k-delete'></span>Delete</a>#}#";
You can do the template inline but I find it easier (particularly for multiple buttons) if you declare constants and then use string.format to concatenate them.
col.Template(o => o).ClientTemplate(string.Format("{0}{1}{2}", ShowUpdateButton, ShowDeleteButton, ShowReverseButton));
The upside is it will work with popup editor whereas jquery hacks will ignore the conditional status when a user cancels out of edit. A cancel from the popup editor will restore the grid row from the viewmodel or wherever Kendo stores it which results in button states from before any jquery/javascript hack. The method above will also auto-wire the standard commands since I copied their HTML output for the client template.
The downside is that if Kendo changes their pattern for command buttons the client template may fail. I tired several other methods besides this one and the downside to this method seems better than the other methods.
Note on Kendo Forums: As of the date of this post, they do not appear to allow people who do not pay for support to post to the forums so I would suggest posting questions here instead. They monitor Stack Overflow and in my experience they seem to answer questions more quickly here.
Use template column instead - via the ClientTemplate method.
Conditional templates are covered here and multiple times on the forums - the Command columns is not that flexible.
As of the December 2018 release of Kendo, you can now conditionally display custom buttons more easily, but it still relies on JavaScript to do its work, this function should be defined before your dataGrid or you'll run into issues.
function showCommand(dataItem) {
console.log("determining to hide or show" + dataItem);
// show the Edit button for the item with Status='New'
if (dataItem.Status == 'New') {
return true;
}
else {
return false;
}
}
Then the code for the Grid.
.Columns (columns => {
columns.Command (
command => command.Custom ("Approve")
.Visible ("showCommand")
.Click ("approveFunc")
)
.Width (100)
.HeaderTemplate ("Actions")
})
You can control custom command button visibility by Visible property.
columns.Command(command => command.Custom("UnlockAccount").SendDataKeys(true).Click().Visible("unlockAccountVisible"))
Visible property accepts JS function name and passes current dataItem as an argument.
JS function that evaluates button visibility:
<script>
function unlockAccountVisible(dataItem) {
// show the UnlockAccount button only when data item property IsLocked == true
return dataItem.IsLocked;
}
</script>
Read more in Show Command Buttons Conditionally kendo-ui documentation article.

MVC jquery MOBILE autocomplete - creates bullets not a drop down menu

I'm having an issue with autocomplete in jquery mobile. I want to create a text input that when the user inputs in it, the cities that correspond with what the user typed in shows up in a drop down menu, similar to how Google Search works.
My problem is that instead of a drop down menu, it just creates a bullet list of all the cities. I have the CSS theme implemented and all the necessary jquery/jquery mobile ui scripts enabled.
After watching the MVC pluralsight tutorial on MVC, I was able to connect to a database of city names and create the following code (these are just snippets):
View
<p>Hotel Location (City): <input type="text" data-autocomplete="#Url.Action("QuickSearch", "Booking")"/></p>
Javascript/Jquery
$(document).ready(function () {
$(":input[data-autocomplete]").each(function () {
$(this).autocomplete({ source: $(this).attr("data-autocomplete") });
});
});
Controller
public ActionResult QuickSearch(string term)
{
testautocompleteDataContext _db = new testautocompleteDataContext();
var cities = _db.CityTests
.Where(r => r.city.Contains(term))
.Take(10)
.Select(r => new { label = r.city });
return Json(cities, JsonRequestBehavior.AllowGet);
}
Thanks! I really appreciate the help :)
My mistake. I actually forgot to add jquery ui in my layout page! Stupid mistake hahaha

SetFoucsOnError in mVC

I am trying to set focus on the control while error occurs. I am use mvc 2.0. In Asp.net we have a property SetFoucsOnError but in MVC what is the substitute of it and how to implement ?
Well I did not get this solution. But i got an alternate option which even works :
$().ready(function() {
$("#Form").submit(function() {
$('.input-validation-error').focus();
$(".input-validation-error").each(function() {
$(this).focus();
});
});
});
I think the easiest way to do this is to use JavaScript.
The example uses jQuery and assumes controls with invalid data have a css class called input-validation-error:
$(function () {
$('form').submit(function() {
$(this).find('input.input-validation-error, select.input-validation-error')
.first()
.focus();
});
});
This will look for all input and select elements with the class input-validation-error, take the first of them and put the focus on it.

Resources