cannot preserve values in the textbox after dropdown on change event - asp.net-mvc-4

I have a problem in preserving the values in the textbox after dropdownlist selected index changed in asp.net mvc. Below is the code for initiating the dropdown onchange event.
#Html.DropDownList("BranchId",null,"Select Branch", new { onchange = "location.href='/User/GetRoles?BranchId='+this.options[this.selectedIndex].value" })
Аnd the roles dropdown binded with the values, but what i typed in the textboxes just above the branch dropdown get lost.
Please help me.
Regards,
Azeem

This is because you are changing your URL location by using location.href. What exactly do you want to achieve? If you need to load certain logic, you might as well bind change event to jQuery function that could load data from the server, and then you do something with that data.
$(document).ready(function() {
$("#BranchId").change(function() {
$.getJSON(YourUrlThatReturnsValues, {data: yourparameter}, function() {
// do some processing here.
});
});
});
The other option is to use Ajax Helpers instead of Html Helpers. Instead of Html.DropDownList you would use Ajax.DropDownList.

You may try something like that:
$(function () {
$('#BranchId').change(function () {
var id = $("#BranchId option:selected").val();
var data = {BranchId: id };
$.get("#Url.Action("User", "GetRoles")", data).done(function(d){
$('.somediv').val(d.rolename)
});
});

Related

Change WebGrid row color conditionally without Jquery/javascript ASP.NET MVC 4

I know this has been asked before but I wanted to ask it in my own way with more clarification. I am trying to conditionally set the background of a td that is created using a webGrid in ASP.NET MVC. I don't see a good way to do this.
So far what I have come up with is this:
grid.Column("DATT", header: "Date", format: (item) => new MvcHtmlString
(
(item.isCurrentlyBackordered)
?
"<div style=\"background-color: red\">Item Backordered</div>"
:
""
)),
This is an okay solution but I would like a more clean look because the webgrid default has a small padding in the table cell so the div won't expand completely to the size of the cell either.
Is there a way to edit the td in any way? I know I can change the background and other style attributes using jquery or javascript but I don't like the idea of having doing duplicate work to first build the table on the server, then on the client side iterate over it again conditionally changing the colors when this should have been completed with the first iteration.
Hope the following answer will help you
grid.GetHtml(columns: grid.Columns(grid.Column(columnName: "DATT", header: "Date",format: #<text> #{
if (#item.isCurrentlyBackordered)
{
<span>Item Backordered</span>
<script>
$("tr:contains('Item Backordered')").css("background-color", "yellow");
</script>
}
}</text>)))
Also you can write this in a common JQuery too
grid.Column("DATT", header: "Date", format: (item) => new MvcHtmlString
(
(item.isCurrentlyBackordered)
?
"<span>Item Backordered</span>"
:
""
)),
JQuery
<script type="text/javascript">
$(function () {
$("tr:contains('Item Backordered')").css("background-color", "yellow");
})
</script>
With the help of Golda's response and here
I was able to create an elegant solution. This solution uses JavaScript/JQuery, as it doesn't seem possible to do it without it but using (to me) a cleaner solution than what I had came across. What I did in the model class (type for List<>()) was add a property that refers to itself and returns an instance cast to its interface like so:
public iTrans This
{
get
{
return this;
}
}
I did this because the webGrid seems to only allow access to the properties and not methods; regardless of access level.
Then in that same model I have a method which will conditionally attach markup for a hidden input field to the data string and return it as an MvcHtmlString object:
public MvcHtmlString htmlColorWrapper(string cellStr, string hexColor = "#ccc")
{
if (isOnBackorder)
{
cellStr = cellStr + "<input type='hidden' class='color' value='" + hexColor + "'/>";
}
return new MvcHtmlString(cellStr);
}
And in the markup (partial view) I make my grid.Column call:
grid.Column("Date", header: "Date", format: (item) => item.This.htmlColorWrapper(item.Date.ToString("MM/dd/yyy"))),
Then I create the JavaScript function(s):
window.onload = function () {
SetFeaturedRow();
};
function SetFeaturedRow() {
$('.color').each(function (index, element) {
$(element).parent().parent().css('background-color', $(element).val());
});
}
The window.onload is needed to point to the SetFeaturedRow() function to set the row colors at page load, the function name, "SetFeaturedRow" is stored in the ajaxUpdateCallback property through the webgrid constructor arguments: new WebGrid(Model ..... ajaxUpdateCallback: "SetFeaturedRow"); Or it can be set through the WebGrid reference, ref.ajaxUpdateCallback = "SetFeatureRow"
This will be used during any ajax call the WebGrid class will make. So for example if there are multiple pages to the webgrid each selection is an ajax call and the row colors will need to be re-updated.
Hopefully this helps someone.

Create custom command to expand client detail template in Kendo UI Grid (MVC)

I've got a nested grid within my grid, and it works perfectly, but the client doesn't like to use the arrow on the left and asked for a button to be added in order to show the child grid.
The example on the Kendo website shows how to automatically open the first row, I just want a way to expand the grid from a custom control in the same way that the left selector does it.
I've got the custom command working, and it executes the sample code, but I just need some help with the javascript required to make it work for the current row.
columns.Command(command =>
{
command.Edit().Text("Edit").UpdateText("Save");
command.Destroy().Text("Del");
command.Custom("Manage Brands").Click("showBrandsForAgency");
And the js with the standard example of opening the first row:
function showBrandsForAgency(e) {
this.expandRow(this.tbody.find("tr.k-master-row").first());
}
Please help by giving me the js required to expand the row clicked and not the first row?
* EDIT *
Modified the solution provided by Atanas Korchev in order to get it to work on only the button and not the whole row.
I'd prefer a solution that uses the function showBrandsForAgency instead of a custom funciton but this does the job:
$(document).ready(function () {
$("#grid").on("click", "a", function (e) {
var grid = $("#grid").data("kendoGrid");
var row = $(this).parent().parent();
if (row.find(".k-icon").hasClass("k-minus")) {
grid.collapseRow(row);
} else {
grid.expandRow(row);
}
});
});
You can try something like this:
$("#grid").on("click", "tr", function(e) {
var grid = $("#grid").data("kendoGrid");
if ($(this).find(".k-icon").hasClass("k-minus")) {
grid.collapseRow(this);
} else {
grid.expandRow(this);
}
});
When using jQuery on the function context (available via the this keyword) is the DOM element which fired the event. In this case this is the clicked table row.
Here is a live demo: http://jsbin.com/emufax/1/edit
Same results just Simpler, faster, and more efficient:
$("#grid").on("click", "tr", function () {
$(this).find("td.k-hierarchy-cell .k-icon").click();
});

Simple store connected list for dojo

Is there a simpler list type than DataGrid that can be connected to a store for Dojo?
I would like the data abstraction of the store, but I don't need the header and cell stucture. I would like to be more flexible in the representation of the datalines, where maybe each line calls an function to get laid out...
You ask a really good question. I actually have a blog post that is still in draft form called "The DataGrid should not be your first option".
I have done a couple thing using the store to display data from a store in a repeated form.
I have manually built an html table using dom-construct and for each.
var table = dojo.create('table', {}, parentNode);
var tbody = dojo.create('tbody', {}, table); // a version of IE needs this or it won't render the table
store.fetch({ // this is a dojo.data.ItemFileReadStore, but you cana dapt to the dojo.Store API
query: {},
onComplete: function(itms) {
dojo.forEach(itms, function(itm, idx) {
var tr = dojo.create('tr', {}, tbody);
// use idx to set odd/even css class
// create tds and the data that goes in them
});
}
});
I have also created a repeater, where I have an html template in a string form and use that to instantiate html for each row.
var htmlTemplate = '<div>${name}</div>'; // assumes name is in the data item
store.fetch({ // this is a dojo.data.ItemFileReadStore, but you cana dapt to the dojo.Store API
query: {},
onComplete: function(itms) {
dojo.forEach(itms, function(itm, idx) {
var expandedHtml = dojo.replace(htmlTemplate, itm);
// use dojo.place to put the html where you want it
});
}
});
You could also have a widget that you instantiate for each item.

dojo - programmatic way to show invalid message

dojo newbie - giving it a shot.
After submitting a form, If an error is returned from the server I would like to show that message on the dijit.form.ValidationTextBox
var user_email = dijit.byId("login_user_email");
user_email.set("invalidMessage", data["result"]["user_email"]);
//need to force show the tooltip but how???
Any help much appreciated.
See it in action at jsFiddle.
Just show tooltip:
var textBox = bijit.byId("validationTextBox");
dijit.showTooltip(
textBox.get("invalidMessage"),
textBox.domNode,
textBox.get("tooltipPosition"),
!textBox.isLeftToRight()
);
Temporarily switch textBox validator, force validation, restore the original validator:
var originalValidator = textBox.validator;
textBox.validator = function() {return false;}
textBox.validate();
textBox.validator = originalValidator;
Or do both at once.
I think you can show the tooltip via myVTB.displayMessage('this is coming from back end validation'); method
you need to do the validation in the validator-method. like here http://docs.dojocampus.org/dijit/form/ValidationTextBox-tricks
you also need to focus the widget to show up the message! dijit.byId("whatever").focus()
#arber solution is the best when using the new dojo. Just remember to set the focus to the TextBox before calling the "displayMessage" method.
I am using dojo 1.10 which works create as follows:
function showCustomMessage(textBox, message){
textBox.focus();
textBox.set("state", "Error");
textBox.displayMessage(message);
}
Dojo reference guid for ValidationTextBox: https://dojotoolkit.org/reference-guide/1.10/dijit/form/ValidationTextBox.html
I know this question is ancient, but hopefully this'll help someone. Yes, you should use validators, but if you have a reason not to, this will display the message and invalidate the field:
function(textbox, state /*"Error", "Incomplete", ""*/, message) {
textbox.focus();
textbox.set("state", state);
textbox.set("message", message);
}
You can call directly the "private" function:
textBox._set('state', 'Error');
You get the same result as #phusick suggested but with less code and arguably in a more direct and clean way.
Notes:
_set is available to ValidationTextBox as declared on its base class dijit/_WidgetBase.
Live demo:
http://jsfiddle.net/gibbok/kas7aopq/
dojo.require("dijit.form.Button");
dojo.require("dijit.form.ValidationTextBox");
dojo.require("dijit.Tooltip");
dojo.ready(function() {
var textBox = dijit.byId("validationTextBox");
dojo.connect(dijit.byId("tooltipBtn"), "onClick", function() {
dijit.showTooltip(
textBox.get('invalidMessage'),
textBox.domNode,
textBox.get('tooltipPosition'), !textBox.isLeftToRight()
);
});
dojo.connect(dijit.byId("validatorBtn"), "onClick", function() {
// call the internal function which set the widget as in error state
textBox._set('state', 'Error');
/*
code not necessary
var originalValidator = textBox.validator;
textBox.validator = function() {return false;}
textBox.validate();
textBox.validator = originalValidator;
*/
});
});

Registering jquery radio button click event doesn't work

I am trying to set a hidden form field with the value of a selected radio button. I have the following code:
$(function () {
// set hidden form field with selected timeslot
$('input[name=["timeslot"]').live("click", (function () {
var valu = $(this).val();
alert(valu);
$("#selectedSlot").val(valu);
}));
});
All radio buttons have the name "timeslot", and I would like to run this function whenever one is clicked. However, the alert box shows blank when I click one of the radio buttons.
UPDATE: Oops! Didn't see the double square brackets. However I fixed it:
$('input[name="timeslot"]').live("click", (function () {
var valu = $(this).val();
alert(valu);
$("#selectedSlot").val(valu);
}));
and I am STILL having the same problem. In fact, the alert box does not even come up any more for some reason.
UPDATE 2: Actually, in my real code I have other events registered in my initiation block besides this one -- if I take out all of them except for the radio button one, it works!
For example, if I have this:
$(function () {
// set hidden form field with selected interviewee
$('#interviewees').live("change", (function () {
var selected = $("#interviewees").val();
$("#selectedInterviewee").val(selected);
}));
// set hidden form field with selected timeslot
$('input[name="timeslot"]').live("click", (function () {
var valu = $(this).val();
alert(valu);
$("#selectedSlot").val(valu);
}));
});
then the radio button click event does NOT fire, though the first one (a dropdown list) does. But if I have the radio button one all by itself, it does. Any ideas????
The input tags look like this:
<input id="slot_7:30-AM" name="timeslot" type="radio" value="slot_7:30-AM" />
I am using IE 8 mostly, but I tried this on Firefox and the same thing happened. What am I doing wrong?
Without seeing your html, I can't be totally sure, but I'm thinking the problem is the selector you're using:
$('input[name=["timeslot"]')
There are at least two problems that might cause issues:
the unclosed square-bracket, and
the use of square brackets inside the attribute selector. Try using: $('input[name="timeslot"]') instead.
Edited in response to comments to the answer, below.
The following seems to work:
$('input[name="timeslot"]').live('click', function() {
var valu = $(this).val();
alert(valu);
$("#selectedSlot").val(valu);
});
JS Fiddle demo.
I am, of course, using a text input, rather than a hidden, but since the selector works on the id it should work regardless of the input type.
OK I got it to work by REVERSING the order of the event registrations:
$(function () {
// set hidden form field with selected timeslot
$('input[name="timeslot"]').live("click", (function () {
var valu = $(this).val();
alert(valu);
$("#selectedSlot").val(valu);
}));
// set hidden form field with selected interviewee
$('#interviewees').live("change", (function () {
var selected = $("#interviewees").val();
$("#selectedInterviewee").val(selected);
}));
});
Ugh. I'm returning to my view that javascript is a flakey mess. But for whatever reason, it does work now. (Both of them work now ... very peculiar.)