C#: How to using global variable with Javascript - c#

everyone!
I'm learning ASP.NET MVC and have some question.
My problem is Passing Data from View to Controller.
This my Code:
#{
string listID = "";
}
and I try to use this variable:
function SubmitDelete() {
var listId = "";
var x = document.getElementsByName("IsCheck");
for (var i = 0; i < x.length; i++) {
if (x[i].checked == true) {
listId += x[i].value + ", ";
};
}
#listID = listId;
return listId;
}
Finalize, I want to pass #listID to Controller:
#using (Html.BeginForm("DeleteChecked", "Category", new { listID }, FormMethod.Post)){ }
It is simple problem about multi delete with checkbox.
Help me, please.

You cannot pass a javascript variable to your controller.
But you can post it as part form data with the help of hidden field.
Better add a hidden field and set it in a Javascript and post
#using (Html.BeginForm("DeleteChecked", "Category", FormMethod.Post)){
Html.HiddenFieldFor(m=>m.MyList, new {#id="my-list-data"})
..other controls and your submit button
}
In a Javascript
function SubmitDelete() {
var listId = "";
var x = document.getElementsByName("IsCheck");
for (var i = 0; i < x.length; i++) {
if (x[i].checked == true) {
listId += x[i].value + ", ";
};
}
$('#my-list-data').val(listId);
}

You cannot do that.
The aspx\ascx\cshtml etc. page is built in the server side while the js is computed on the client's side.
You can add C# string to js functions but they will be hard coded when they get to the client.
All the C# expression are evaluated before they get to the client and before the js is computed.
Here's an example:
This is what you see on the aspx\ascx\cshtml file.
<%
string str = 'test';
%>
function jsFunc(){
var myVar = '<%=str%>';
}
This is what the client gets:
function jsFunc(){
var myVar = 'test';
}

Related

Bootstrap Selectpicker multiselect doesn't keep selection after submit

I am using the bootstrap selectpicker for a multiselect dropdown menu to filter items of a table in a mvc5 web app. Everything works fine so far, but i am having trouble to keep the selected filters selected after submitting. So i can read the selected filters in the controller, but after that, there is only the first previously selected filter still shown as selected after the submit. I want all chosen filters to be still selected. How can I reach this?
Here ist my Code, the ViewModel contains:
public MultiSelectList AvailableUser_ID { get; set; }
private List<string> _selectedUserId = new List<string>();
public List<string> SelectedUserId
{
get { return _selectedUserId; }
set { _selectedUserId = value; }
}
The Controller (Post):
[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult Index([Bind(Include = "SelectedUserId,SelectedUserInteractionTypesId")] IndexUserInteractionViewModel indexUserInteractionViewModel)
{
indexUserInteractionViewModel.UserInteractionViewModels = new List<UserInteractionViewModels>();
indexUserInteractionViewModel.AvailableUser_ID = new MultiSelectList(db.AspNetUsers.ToList(), "Id", "Email", indexUserInteractionViewModel.SelectedUserId);
// Filter Function: selectedUserId contains all the Ids of the previously selected filters
foreach (string selectedUserId in indexUserInteractionViewModel.SelectedUserId)
{
if (userInteraction.AspNetUsers_Id.Equals(selectedUserId))
// ...
}
}
And the View:
<script type="text/javascript">
$(document).ready(function () {
$('.selectpicker').selectpicker();
});
</script>
<th>#Html.DropDownListFor(Model => Model.SelectedUserId, Model.AvailableUser_ID as MultiSelectList, new { #id = "userFilter", #class = "selectpicker", #multiple = "mulitple", data_live_search = "true" })</th>
So how can I keep the Selection selected?
Unfortunately I have little js-knowledge and i am assuming that i could solve it in the js-script. I am hoping for some experts here. Thank you!
A colleague of mine found a solution, this is what works:
var selectedList = #Html.Raw(Json.Encode(Model.SelectedUserId));
if(selectedList.length > 0){
var result = '[';
for (i = 0; i < selectedList.length; i++) {
result += '"' + selectedList[i] + '",';
}
result = result.slice(0, -1); //remove last comma
result += ']';
$('.selectpicker').selectpicker('val', JSON.parse(result1));
}else{
$('.selectpicker').selectpicker();
}

How to get value of selected checkboxlist items using javascript in asp.net

I am working on an asp.net project in which i have a checkboxlist which i have bound using
DataTable dt = new Process_Hotels().SelectAllFacilty();
if (dt.Rows.Count > 0)
{
cblHotelFacility.DataSource = dt;
cblHotelFacility.DataTextField = "Facility";
cblHotelFacility.DataValueField = "ID";
cblHotelFacility.DataBind();
foreach (ListItem li in cblHotelFacility.Items)
{
li.Attributes.Add("JSvalue", li.Value);
}
}
and now i want to get selected value ID of checkboxlist using javascript on button click.For that i have following javascript code on button click:
<script type="text/javascript">
function test() {
var checkList1 = document.getElementById('<%= cblHotelFacility.ClientID %>');
var checkBoxList1 = checkList1.getElementsByTagName("input");
var checkBoxSelectedItems1 = new Array();
for (var i = 0; i < checkBoxList1.length; i++) {
if (checkBoxList1[i].checked) {
checkBoxSelectedItems1.push(checkBoxList1[i].value);
//alert('checked:' + checkBoxSelectedItems1.push(checkBoxList1[i].getAttribute("JSvalue")).value);
alert('checked - : ' + checkBoxList1[i].value)
}
}
}
</script>
but the on clicking button the selected checkboxlist is showing 0. I want to get ID of selected checkboxlist items.Please help.
Try this :
<script type = "text/javascript">
function GetCheckBoxListValues(chkBoxID)
{
var chkBox = document.getElementById('<%= cblHotelFacility.ClientID %>');
var options = chkBox.getElementsByTagName('input');
var listOfSpans = chkBox.getElementsByTagName('span');
for (var i = 0; i < options.length; i++)
{
if(options[i].checked)
{
alert(listOfSpans[i].attributes["JSvalue"].value);
}
}
}
</script>
Try debugging
for (var i = 0; i < checkBoxList1.length; i++) {
console.log(checkBoxList1[i])
if (checkBoxList1[i].checked) {
checkBoxSelectedItems1.push(checkBoxList1[i].value);
//alert('checked:' + checkBoxSelectedItems1.push(checkBoxList1[i].getAttribute("JSvalue")).value);
alert('checked - : ' + checkBoxList1[i].value)
}
}
Check to see id console.log() gives you any information about the object by pressing F12 on console window. Install firebug plugin for Firefox.
May this code help you:
function CheckBoxCheckOrNot(jobskill) {
var c = document.getElementById(jobskill).getElementsByTagName('input');
for (var i = 0; i < c.length; i++) {
if (c[i].type == 'checkbox') {
if (c[i].checked) {
alert('checkbox checked');
}
else {
alert('checkbox unchecked');
}
}
}
}
note: jobskill is a container id which contain all check boxes.

How to set the display value and the value of autocompleted textbox?

I've made an auto-completion in a textbox using Jquery as follows:
$(document).ready(function () {
$('#searchCollabo').autocomplete({
source: '#Url.Action("AutocompleteCollabo")'
});
});
So the data come from the method AutocompleteCollabo which looks like that:
public ActionResult AutocompleteCollabo(string term)
{
int NumDossier = StructureData.DonneNumDossier((string)Session["NumCRPCEN"], (string)Session["MotDePasse"]);
List<Contact> ListeContacts = StructureData.DonneListeElementDossier(NumDossier);
Contact[] tabContacts = new Contact[ListeContacts.Count()];
int count = 0;
foreach (Contact contact in ListeContacts)
{
tabContacts[count] = contact;
count++;
}
var collaborateurs = tabContacts;
var collaborateurFiltres = collaborateurs.Where(
item => item.Nom.Contains(term) || item.Fonction.Contains(term)
);
return Json(collaborateurFiltres, JsonRequestBehavior.AllowGet);
}
The returned json contains a list of object as below:
[{"ListeFonctions":[],"IdContact":91264,"Nom":"solecki","Prenom":"hubert","Email":"hsolecki#mail.c"}]
Now I would like to set the display name (Name + function) and the value which I want to get when I select a row of the auto-completion. Do you have an Idea ?
I found out how to do it, it may help.
The function that I'm calling throught an Ajax call:
public ActionResult AutocompleteCollabo(string term)
{
int NumDossier = StructureData.DonneNumDossier((string)Session["NumCRPCEN"], (string)Session["MotDePasse"]);
List<Contact> ListeContacts = StructureData.DonneListeElementDossier(NumDossier);
var tabContactFull = ListeContacts.Where(contact => contact.Nom.Contains(term) || contact.Prenom.Contains(term) || contact.Fonction.Contains(term));
var tabInfosUtiles = tabContactFull.Select(contact => new { label = contact.Nom + " " + contact.Prenom + " ("+contact.Fonction+") ", value = contact.Nom + " " + contact.Prenom + " ("+contact.Fonction+") ", id = contact.IdContact }).ToArray();
// We set our needed informations with a title like "Label", "Value"
// So the auto-complete can find by itself which data to display and which are for the value
return Json(tabInfosUtiles, JsonRequestBehavior.AllowGet);
}
My Ajax call and the success event:
$(document).ready(function () {
$('#searchCollabo').autocomplete({
source: '#Url.Action("AutocompleteCollabo")',
select: function (event, ui) {
$("#idElement").val(ui.item.id);
// If you want to get the value : ui.item.Value
// If you want to get the label : ui.item.Label
}
});
});
Hope it helps some of you !

return value from javascript should be assigned to an array in C#

I have a javascript function that returns an array.
I would like to know
(a) how to call the Javascript function in OnInit or Onload
(b) The javascript function returns an array and I want it to be stored within an array in my c# code.
Please suggest.
Thanks.
Update1: Javascript function is something like below.
function RenderUrl()
{
var url = "http://myurl.com/mypage?Id=420&Width=30"; //this is a dummy url.
var qsBegin = url.indexOf("?");
var qsPattern = new RegExp("[?&]([^=]*)=([^&]*)", "ig");
var match = qsPattern.exec(url);
var params = new Array();
while (match != null)
{
var matchID = match[1];
if ( matchID.charAt(0) == "&" )
{
matchID = matchID.substr(1);
}
if ( params[match[1]] != null && !(params[match[1]] instanceof Array) )
{
var subArray = new Array();
subArray.push(params[match[1]]);
subArray.push(unescape(match[2]));
params[match[1]] = subArray;
}
else if ( params[match[1]] != null && params[match[1]] instanceof Array )
{
params[match[1]].push(unescape(match[2]));
}
else
{
params[match[1]]=unescape(match[2]);
}
match = qsPattern.exec(url);
}
return params;
}
Update 2: My c# code so far (not working as expected but I am checking currently)
private void ParseUrl(string Url)
{
int WhereToBegin = Url.IndexOf("?");
string pattern = #"[?&]([^=]*)=([^&]*)";
Regex rgx = new Regex(pattern, RegexOptions.IgnoreCase);
MatchCollection matches = rgx.Matches(Url);
while (matches != null)
{
string matchID = matches[0].ToString();
if (matchID.Substring(0, 1) == "&")
{
matchID = matchID.Substring(1);
}
//Push to the new array named PARAMS here (under construction)
..
..
//End array construction.
matches = rgx.Matches(Url);
}
//Finally return the array once it is working fine.
}
The javascript that you posted just extracts the parameters from the URL of the page. You don't need to use javascript to get that information in ASP.NET, you can get it from C# directly by looking at Request.QueryString (among other ways)
Last time I checked, you cannot call client side code from server side code.

Javascript tabs: call event onclick

I got some code I need to change. it is build by others, and not very neat...
There is a javascript tabcontrol, containing 4 tabs, which contains gridviews.
All the 4 gridviews are build during the load of the page, but I want them to load, when you activate the tabs (as it is possible to watch the side, while you don't need the specific gridviews to see)
So, my question is: how to call an event (that loads the gridview) from an javascript tab?
how the tabs are generated: (generated code, I know, horrible)
var obj = 0;
var oid = 0;
var otb = 0;
var myTabs = new Array();
var myTabitems = new Array();
var myTabitem = new Array();
var myTabContent = new Array();
var myLists = new Array();
function showTabContent(tab)
{
tb = tab.obj;
id = tab.nr;
if (myTabs[tb].oid != -1)
{
myTabs[tb].myTabContent[myTabs[tb].oid].style.display = 'none';
myTabs[tb].myTabitem[myTabs[tb].oid].className -= " active";
}
myTabs[tb].myTabContent[id].style.display = 'block';
myTabs[tb].myTabitem[id].className += " active";
myTabs[tb].oid = id;
}
function boTabs()
{
var myBlocks = new Array();
myBlocks = document.getElementsByTagName("div");
var stopit = myBlocks.length;
for (var g = 0; g < stopit; g++)
{
if (myBlocks[g].className == "tabs")
{
myTabs.push(myBlocks[g]);
}
}
var stopit2 = myTabs.length;
for (var i = 0; i < stopit2; i++)
{
myTabs[i].myLists = myTabs[i].getElementsByTagName("ul");
if (myTabs[i].myLists[0].className == "tabs")
{
myTabs[i].myTabitems = myTabs[i].myLists[0].getElementsByTagName("li");
}
var stopit3 = myTabs[i].myTabitems.length;
myTabs[i].obj = i;
myTabs[i].myTabitem = new Array();
myTabs[i].myTabContent = new Array();
for (var j = 0; j < stopit3; j++)
{
myTabs[i].myTabitem.push(myTabs[i].myTabitems[j]);
myTabs[i].myTabitem[j].nr = j; myTabs[i].myTabitem[j].obj = i;
myTabs[i].myTabitem[j].onclick = function() { showTabContent(this); };
}
var myTabDivs = myTabs[i].getElementsByTagName("div");
for (var j = 0; j < myTabDivs.length; j++)
{
if (myTabDivs[j].className == "tabcontent")
{
myTabs[i].myTabContent.push(myTabDivs[j]);
}
}
myTabs[i].myTabitem[0].className += " active";
myTabs[i].myTabContent[0].style.display = 'block';
myTabs[i].oid = 0;
myTabDivs = null;
}
myBlocks = null;
}
onload = boTabs;
I would change it entirely to use JQuery Tabs and JQuery AJAX to load the grids
If you want a JS solution, you have to build the gridview table yourself using JS code... If you want the server to do the work, you need an UpdatePanel, and make use of the client _doPostBack method. If you like this approach, the Ajax Control Toolkit tab container can be configured to postback to the server whenever the tab changes, which you can wrap this control with an update panel, and it looks like everything is being done with JS code. Alternatively, you can also use a web service that binds a gridview and returns the HTML too... not tried that yet, but seen it done.
HTH, if you let me know what option you prefer, I could update accordingly.
I now got the tabcontrol made by JQuery and CSS.
at this moment all 4 gridviews are bound at Page_Load, but, as it takes time to run te sproc's behind the gridview, it takes a few seconds. Therefore I want to load them on tabclick... The UpdatePanel seems the best way...
JQuery:
$(document).ready(function()
{
//When page loads...
$(".tab_content").hide(); //Hide all content
$("ul.tabs li:first").addClass("active").show(); //Activate first tab
$(".tab_content:first").show(); //Show first tab content
//On Click Event
$("ul.tabs li").click(function()
{
$("ul.tabs li").removeClass("active"); //Remove any "active" class
$(this).addClass("active"); //Add "active" class to selected tab
$(".tab_content").hide(); //Hide all tab content
var activeTab = $(this).find("a").attr("href"); //Find the href attribute value to identify the active tab + content
$(activeTab).fadeIn(); //Fade in the active ID content
return false;
});
});

Categories

Resources