I am implementing this JQuery UI multiselect from
http://www.erichynds.com/jquery/jquery-ui-multiselect-widget/
I have managed to get it to use in my asp.net page, but for some reason after postback, the selected text shows only the last element checked.
Here is my Code
$("document").ready(function () {
$("#ListBox1").multiselect({
noneSelectedText: 'Select',
selectedList: 200
});
$("#ListBox2").multiselect({
noneSelectedText: 'Select',
selectedList: 200
});
function GetSelectedListBox() {
var array_of_checked_values = $("#ListBox1").multiselect("getChecked").map(function () {
return this.value;
}).get();
var array_of_checked_values1 = $("#ListBox2").multiselect("getChecked").map(function () {
return this.value;
}).get();
$("#HiddenField1").val(array_of_checked_values);
$("#HiddenField2").val(array_of_checked_values1);
}
});
<body>
<form id="form1" runat="server">
<div style="font:12px Helvetica, arial, sans-serif;">
<asp:ListBox ID="ListBox1" runat="server"></asp:ListBox>
<asp:ListBox ID="ListBox2" runat="server"></asp:ListBox>
<asp:HiddenField ID="HiddenField1" runat="server" />
<asp:HiddenField ID="HiddenField2" runat="server" />
</div>
<div>
<asp:Button ID="btn1" runat="server" Text="Press" OnClientClick="GetSelectedListBox();" onclick="btn1_Click" />
</div>
</form>
</body>
in my server side code
ListBox2.DataSource = dt;
ListBox2.DataTextField = "Id";
ListBox2.DataValueField = "ListValue";
ListBox2.DataBind();
protected void btn1_Click(object sender, EventArgs e)
{
Response.Write(HiddenField1.Value);
Response.Write(HiddenField2.Value);
}
Any ideas why is it showing only last selected element but the interesting this the values in the HiddenField is displaying "Value1,Value2,Value3, value21" whereas the widget box is only showing value21, and only value21 is disaplyed as checked in the widget when all the elements where checked prior to postback
Thanks
I have make a temporal fix, I already know is not the best solution, but it work until I find the right way to do it.
I have create a hidden field for each select and before submit the form I set the hidden fields with the value of options.
So I can get this values on the controller.
$('#muestraForm').submit(function() {
$("#hidden_temporal_field").val($("#select_field").val());
return true;
});
I was actually just having that same problem.
Try using a listbox with the selection mode as Multiple, I have a postback in my page and the values stay there
<asp:ListBox ID="ListBox1" SelectionMode="Multiple" runat="server"></asp:ListBox>
also, there doesn't seem to be a SelectedItem*s* for a listbox in asp.net only on forms so you need to do this manually something like this
private String GetSelectedItems(ListBox listbox)
{
String SelectedValues = "";
foreach ( ListItem item in listbox.Items)
{
if(item.Selected == true)
SelectedValues = SelectedValues + "," + item.Text ;
}
if (SelectedValues.Length > 1)
SelectedValues = SelectedValues.Remove(0, 1);
return SelectedValues;
}
This works for me values stay after each post back and I can access the list of selected values in code behing :) , let me know if it helps you
Related
My form I am designing with MVC 4 has mutiple DIVS with many elements in each one. My objective is to open/close DIVS as the user completes the fields. However, I want to use the unobtrusive validation on each DIV, rather than the whole form. Is that possible without checking each element individually? Maybe using a DIV ID or something? I don't want to build this massive function to check each and every element in each DIV just so the user can move to the next DIV.
I am trying this and it is not working:
var elems = [];
var valid = true;
("#Contact").find('.text_input').each(function() {
elems.push(this.id);
}
for (var i = 0; i<= elems.length; i++) {
if ($("#" + elems[i]) != undefined) {
$("#form1").validate().element("#" + elems[i]))
if ($("#" + elems[i]).valid()) {
}
else {
valid = false;
}
}
}
but I keep getting an undefined error. The elements in the DIV that have the class text_input are the ones with validation required.
You can validate individual controls using Validator.element(element) - see documentation here, so you could use the following approach (you haven't posted the views html so can't write the actual code for you)
In the Next button click event
Select all the the controls within the
associated div - e.g. var controls = $(this).closest('div').find('input, textarea, select');
In an $.each loop, call $("form").validate().element($(this));
If necessary, test if valid with $(this).valid();
If everything is valid, hide the current div and display the next
Edit (example added)
View
<div class="section">
<h2>Section 1</h2>
.... // Your inputs and validation
#Html.LabelFor(m => m.SomeProperty)
#Html.TextBoxFor(m => m.SomeProperty)
#Html.ValidationMessageFor(m => m.SomeProperty)
<div class="error"></div>
<button type="button" class="next">Next</button>
</div>
<div class="section">
<h2>Section 2</h2>
.... // Your inputs and validation
<div class="error"></div>
<button type="button" class="next">Next</button>
</div>
<div class="section">
<h2>Section 3</h2>
.... // Your inputs and validation
<div class="error"></div>
<button type="submit" class="next">Submit</button> // submit button for last section
</div>
CSS
.section:not(:first-of-type) {
display:none;
}
Script
$('button').click(function () {
var container = $(this).closest('.section');
var isValid = true;
$.each(container.find('input'), function () {
$('form').validate().element($(this));
if (!$(this).valid()) {
isValid = false;
return false;
}
});
if (isValid) {
container.next('.section').show().find('input').first().focus();
container.hide();
} else {
container.find('.error').text('please complete');
}
});
I´ve been struggling to make my Kendo Datepicker without user-text-input and the only solution I´ve come up with was making the tag "readonly". However I want to be able to select the date from the selector with the mouse without being able to input text directly to the picker, therefore making the datepicker readonly but selectable.
Any ideas how?
<div>
#(Html.Kendo().DatePicker()
.Start(CalendarView.Year)
.Name("DatePicker")
.Value(DateTime.Now.AddDays(-365))
.Max(DateTime.Now)
.HtmlAttributes(new { style = "width: 125px;" })
.Events(e => e.Change("onDateChange")))
</div>
After a while I found a very simple solution using javascript. I simply declared a script that prevents any user input without disabling or making the input readonly. Something like this:
$("#inputId").keypress(function (evt) {
var keycode = evt.charCode || evt.keyCode;
if (keycode == 9) { //allow Tab through
return true;
} else {
return false;
}
});
It was easier than I thought :)
########### EDITED ####################
As suggested in a comment, it is probably not good practice to suppress all the keystrokes so I will paste almost the same code but suggesting that I open the datePicker instead (but still kind of suppressing the user text input as well).
$("#inputId").keypress(function (evt) {
var keycode = evt.charCode || evt.keyCode;
if (keycode == 9) { //allow Tab through
return true;
} else {
// Allow the datepicker to open instead
var datePicker = $("#inputId").data("kendoDatePicker");
datePicker.open();
return false;
}
});
You can do something like this:
#(Html.Kendo().DatePicker().Name("FollowUpDate").HtmlAttributes(new{onkeydown="javascript:return false;" }))
when someone clicks the datepicker it returns false hence does not allow to type anything while it still remains selectable.
If you want to just select data from opening calendar which kendoDatePicker show you but user not allow to enter date
<link href="http://cdn.kendostatic.com/2015.1.408/styles/kendo.common.min.css" rel="stylesheet" />
<link href="http://cdn.kendostatic.com/2015.1.408/styles/kendo.default.min.css" rel="stylesheet" />
<input type="text" onkeydown="return false" placeholder="Enter Date" class="DatePicherKendo" />
<script src="~/bower_components/DataPicker-Kendo/JalaliDate.js"></script>
<script src="~/bower_components/DataPicker-Kendo/kendo.web.js"></script>
$(".DatePicherKendo").kendoDatePicker();
Add a maxlength attribute of 0 in HtmlAttributes.
Quiz project, a question has a radiobuttonlist with either 2 items(T/F) or 4 items (a,b,c,d)
number of questions varies. Panel is used to show only one question at a time (show/hide).
after answering all questions user clicks on submit button and all answers should be saved in database. In code behind selecteditem is always null and value is always empty string.
<asp:DataList ID="dtQuestion" runat="server" RepeatDirection="Vertical" OnItemDataBound="FormatDataListRow" >
<ItemTemplate>
<asp:Panel id="panel" runat="server" BorderColor="#536895" BorderStyle="Solid" BorderWidth="1" style="display: none;" EnableViewState="true">
<asp:Label id="lblQuestionDesc" runat="server" Text="" ></asp:Label>
<asp:RadioButtonList id="rbl" runat="server" EnableViewState="true" > </asp:RadioButtonList>
</asp:Panel>
</ItemTemplate>
</asp:DataList>
on submit click. I call a function that search the page for RBL I am able to see their correct ID's and list items but nothing is selected.
string id;
if (c.GetType().ToString().Equals("System.Web.UI.WebControls.RadioButtonList"))
{
if (c.ID != "rbl")
{
id = c.ID;
al.Add(id + "," + ((RadioButtonList)c).SelectedItem.Value); //SelectedValue); //
}
}
It seems that you're populating the RadioButtonList on the page load -
If so - make sure you surround your population of the RadioButtonList with an
If/Then/Postback block:
if not Page.IsPostBack then
' populate your RBL
end if
eg:
if (!IsPostBack)
{
loadradiobuttonlist();
}
Try accessing the submitted value like this:
this.Request.Form[((RadioButtonList)c).UniqueID]
During debugging you can always check what values you've got in this.Request.Form collection.
This is my action :
[HttpPost]
public ActionResult AddDispo(string idv, string dd, string df)
{
try
{
Models.indisponible model = new Models.indisponible();
model.Dd = Convert.ToDateTime(dd);
model.Df = Convert.ToDateTime(df);
model.idv = idv;
entity.indisponible.AddObject(model);
entity.SaveChanges();
TempData["Resultat"] = "La nouvelle date a été ajouté courrectement";
return RedirectToAction("Dispo", "Agence", new { idv = idv});
}
catch (Exception)
{
TempData["Resultat"] = "Une erreur se produiset Vielliez ressaiyer";
return RedirectToAction("Dispo", "Agence", new { idv = idv});
}
}
I want to call this action without using Html.beginForm from my view, i have made this trial but it hasn't worked :
<%: Html.Action("Accepter", "Adddispo", new { id = Model.idv, dd = Model.Dd, df = Model.Df })%>
Your Action method is of type HTTPOST. So you need a form posting for that action to get invoked. If you do not wish to use the form tag in your view, you may use jQuery to do a POST.
The below example does a post when user clicks on a button woth ID btnPost.
HTML ( Content of Your View)
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.7.2/jquery.min.js"></script>
</head>
<body>
Name : <input type="text" id="txtName" /> <br/>
Age: <input type="text" id="txtAge" /> <br/>
Place : <input type="text" id="txtPlace" /> <br/>
<input type="button" value="Save" id="btnPost" />
<script type="text/javascript">
$(function(){
$("#btnPost").click(function(e){
e.preventDefault(); // preventing the default button submit behaviour
var name=$("#txtName").val(); //reading the text box values
var age=$("#txtAge").val();
var place=$("#txtPlace").val();
$.post("YourController/AddDispo", { idv :name, dd : age, df=place} ,function(data) {
//Do whatever with the the response. may be an alert
alert(data);
});
});
});
</script>
What it does
1) In the head section of the document, we included the reference to the jQuery library. I am including a reference from the google CDN. You may change that to include your local copy. If you are working with ASP.NET MVC, the default project template has this under the Scripts folder(version number may be different).
2) In the document ready event ($(function(){..) we are binding some functionality to the button which has an ID btnPost. We are binding the functionality on the click event. So whenever user clicks on that button, that piece of code will be executed.
3) We are reading the text box values, and making use of the post method of jQuery. It will post the data we are passing ( we are passing the values of text boxes here) to the action method. once the action method returns something back to the calle, it will be stored in the data variable. you can do further things (show some message to user/ reload some content) after checking the value of that.
Action link will always send a "GET" request. Either remove that [HttpPost] attribute from your controller action, or use a similar technique suggested by shyju. Action link has some issues with windows events, so you should stick to stylized buttons unless there is specific need for anchors. A sample styling will be :
#mybutton input[type=submit] {
background: none;
padding: 0px;
font-family: arial;
font-size: 1em;
cursor: pointer; // to make it look like link
border: none; // --- " -----
}
I have a method in my controller like this
public string UpdateResource()
{
Thread.Sleep(2000);
return string.Format("Current time is {0}", DateTime.Now.ToShortTimeString());
}
I have a html button in my view page and when I click on that I want a loading gif image to appear and then disappear after 2000ms. Below is my html
<input type="button" id="btnUpdate" value="Update" />
<img id="loading" src="/Images/ajax-loader.gif" alt="Updating ..." />
<div id="result"></div>
How can I call the controller method. I have seen Html.ActionLink but I want this on button click and not a hyperlink.
Please help
First change to UpdateResource method. Now it returns ActionResult:
public ActionResult UpdateResource()
{
Thread.Sleep(5000);
return Content(string.Format("Current time is {0}", DateTime.Now.ToShortTimeString()));
}
We have to hide image when document is loaded so we change image tag to:
<img id="loading" src="../../Content/progress.gif" alt="Updating ..." style="display: none;" />
We have added style="display:none".
Then we are using jQuery:
<script type="text/javascript">
$(document).ready(
function() {
$('#btnUpdate').click(
function() {
$('#loading').show();
$.get('<%= Url.Action("UpdateResource") %>', {},
function(data) {
$('#result').html(data);
$('#loading').hide();
});
}
);
}
);
</script>
When document is loaded, we are setting click action to your button. It shows progress and then uses ajax to get ActionResult. When ActionResult comes back, we are hiding progress and setting content of #result div with returned data.