ASP.NET MVC DropDownlist event to partial view - javascript

I have a dropdownlist like
#Html.DropDownList("ProjectsList")
and a link is near it
#Html.ActionLink("Change Project", "ChangeProject", new { code = param }, new { id = "myLink2" })
and also a dropdown list for DB names which is accordingly changing to the previous list
#Html.DropDownList("Databaselist")
What I want is when I click the Change Project link it will work the ChangeProject function on c# with selected dropdownlist parameter(I used select2 dd list) and run the "GetDbList" function on c#

Its difficult to manage from server side rendering because if some how you got your dropdownlist value inside actionlink that will be only the value that selected on page load.
So the best ways to get dynamics values like you are looking for is to use script.
<a class="ChangeProject" href="#">Change Project</a>
$('.ChangeProject').on('click', function(){
var url = '#Url.Action("project", "GetDbList", new { id= "----" })';
url = url.replace("----", $('#ProjectsList').val()); //here you will get selected id from dropwon
window.location = url;
});

I think u can use javascript for this (this code can inspire you to solve):
<ul>
<li><a onClick="myTestFunction(this)">ID1</a></li>
<li><a onClick="myTestFunction(this)">ID2</a></li>
<li><a onClick="myTestFunction(this)">ID3</a></li>
<li><a onClick="myTestFunction(this)">ID4</a></li>
</ul>
<script>
function myTestFunction(e)
{
///THERE U CAN IMPLEMENT CODE wich must update link for a tag or do some redirect
///alert(e.textContent);
var getAtagContent=e.textContent;
window.location = "/ChangeProject?id="+getAtagContent;
}
</script>

Related

Dynamically appending value to a link produces wrong results

I have this simple table containing user details (user id in the provided example). There's a link available for each record. This link (in real) is dynamically generated based on no.of records. each record will have a link. And upon clicking this link, that corresponding user's id has to be passed (appended) to another link (which I refer as user link in the example).
My HTML Code:
<a id="abc" href="aa/">User Link</a>
<hr>
<table border="1">
<tr>
<td><a id="xyz" data-userid="100" href="#">first user</a></td>
<td>100</td>
</tr>
<tr>
<td><a id="xyz" data-userid="200" href="#">second user</a></td>
<td>200</td>
</tr>
<tr>
<td><a id="xyz" data-userid="300" href="#">third user</a></td>
<td>300</td>
</tr>
</table>
jQuery:
$(document).on('click','#xyz',function(e){
var uid = $(this).attr('data-userid');
$('#abc').attr('href',$('#abc').attr('href')+uid);
});
I am appending the user id to the User Link based on the above jQuery code.
This is what I am trying to achieve:
<a id="abc" href="aa/100">User Link</a> for first user
<a id="abc" href="aa/200">User Link</a> for second user
<a id="abc" href="aa/300">User Link</a> for third user
which I get partially.
Issue:
When I click a second link after clicking a previous one, both the values are appending to the end of User Link.
For example, If I click first user initially, User Link becomes
<a id="abc" href="aa/100">User Link</a>
and then if I click second user, User Link becomes
<a id="abc" href="aa/100200">User Link</a>
and so on...which is not what I am trying to get.
Where did I make mistake???
FIDDLE.
P.S: use Inspect Element from browser to see this mess in live action.
Few issues:
Change IDs to classes in your markup class="xyz" and in the click handler .xyz
Store the initial href value to access it on subsequent clicks.
Updated Fiddle
var initHref = $('#abc').attr('href')
$(document).on('click','.xyz',function(e){
e.preventDefault(); // Prevent default action of `<a>`
var uid = $(this).attr('data-userid'); //or $(this).data('userid');
$('#abc').attr('href',initHref+uid);
});
You may want to store the href of the user link and use it later to append the new value, like below.
P.S. please change ID xyz to class
Demo#Fiddle
$(function() {
var userLink = $('#abc')[0];
var linkHref = userLink.href;
$(document).on('click','.xyz',function(e) {
e.preventDefault(); //Cancels the default behaviour
var uid = $(this).attr('data-userid');
userLink.href = linkHref + uid;
});
})
The same way you used data-userid, you may use data-href in the first link to store your initial and unmodified url.
And then use something similar to:
$(function() {
$(document).on("click", ".xyz", function (e) {
e.preventDefault();
var userLink = $("#abc");
userLink.attr("href", userLink.attr("data-href") + $(this).attr("data-userid"));
});
});
First and foremost, do not have multiple elements with the same id. See
Why is it a bad thing to have multiple HTML elements with the same id attribute?
Second, store the initial href in a var like
var initialHref = $('#abc').attr('href');
and change
$('#abc').attr('href',$('#abc').attr('href')+uid);
to
$('#abc').attr('href',initialHref+uid);
See it working here

HTML5, Knockout url redirect function

I have created an HTML5 application which uses knockoutjs to make call to a restful service and get/post JSON messages.
This is my first application using HTML5 so I am not sure how to implement a URL redirect.
In the application I have two html pages, one is a DataGrid page which shows all the data received by doing a get rest call. I have added a hyperlink to one the field in the display which I would like to use to redirect to the details page and make the rest call to get data for that particular id and display it in the editable page later would like to save the changes.
UserGridPage.html
<tbody data-bind="foreach:userList">
<tr>
<td><a data-bind="attr:{href: userInfoUrl()}, text:userInfoId"></a></td>
<td data-bind="text: UserName" ></td>
</tr>
UserGridPage.js
MyUserInfoViewModel = function () {
var self = this;
self.userList = ko.observableArray();
$.getJSON("http://localhost:8080/user/webresources/userinfo/").
then(function (userinfos) {
$.each(userinfos, function () {
self.userList.push({
userInfoUrl:ko.observable('/USERUI/UserEntry.html#'+this.userInfoId),
userInfoId:ko.observable(this.userInfoId),
policyHolderEmail: ko.observable(this.policyHolderEmail),
});
});
});
I would like to know how can UserEntry page would know which Id is getting passed to its page and also how would I make the rest call to have the Id passed to the restful URL.
Appreciate any help with code samples, links etc..
Thanks
You should be trying like this
View :
<ul data-bind="foreach: items">
<li>
<a data-bind="attr: { href: id }, text: name,click:function(){alert(id)}"></a>
</li>
</ul>
ViewModel :
var viewModel = {
items: [{'id':1,'name':"one"},{'id':2,'name':"two"},{'id':3,'name':"three"}]
};
ko.applyBindings(viewModel);
Sample working fiddle here
In your userEntry.html, if you want to get the id value passed:
<script>
var id = window.location.hash;
</script>
I remember firefox has a slightly different behaviour in that it decodes URL encoded characters in the fragment, so if you want the raw content, you can also consider using:
<script>
var id = window.location.href.split("#")[1];
</script>
Not sure how you can get the parameter from the URL with javascript, but if you are willing to use PHP you could get the Id parameter with $_REQUEST['Id'] an use it to generate your new REST call.
So your href would be something like "/USERUI/UserEntry.php?Id=5"
To use that variable in javascript on your UserEntry page you can do something like:
<script>
var id = <?php $_REQUEST['Id']; ?>
//generate your restful query here.
</script>

How to get li tag value by javascript or jquery

I need to get li value onclick function in php ...and want to store that in php session..
i used my code for this but this is not working....
i need to know that how to get li value on click function in java script..
i NEED to get li tag value of on click function and want to store in php session by js or jquery
<li class="atleta" value="100" >
<a href="#" >Vendor Registration</a>
</li>
$('.atleta').click(function(e) {
var <?php $_SESSION['VENDR']?> = $(this));
});
Don't mix server side and client side technologies.Instead to php session i will recommend to use localStorage instead and store clicked li value in it as shown :-
$('.atleta').click(function(e) {
localStorage.setItem('lival',$(this).val());
});
and in order to get data stored in localStorage use this :-
var livalue = localStorage.getItem('lival');
Reference
Or Instead of localStorage you can use sessionStorage also(their basic usage is same except for some difference refer here)
try this -
$('.atleta').click(function(e) {
e.preventDefault(); //if needed
var <?php $_SESSION['VENDR']?> = $(this).children('a').text();
});
i used this and its working..
<li id="atleta" value="18" onclick="vendorData();">
<a href="#" >Vendor Registration</a>
</li>
<script>
function vendorData(){
var h = document.getElementById('atleta').value;
localStorage.setItem("vendor", h);
var ven = localStorage.getItem("vendor");
}
</script>
You can store your variable in cookies, so you can set it via jQuery and get in php later

What is the best was to access a property of a deeply embedded asp.net control using client side java script?

I could use some advice please.
THE SCENARIO
I have a tabbed control on the page.
There an update panel on each tab.
Inside each update panel is an instance of a custom Web part (asp.net)
I need to get the parameter value of the report viewer embedded in a user control in the Web part.
I need to retrieve this value using java script on the client side.
To be clear, I don't want to pass up variables using hidden controls or similar methods.
Can I reference the property of the bottom most object, a report viewer?
THE UPDATE PANEL CODE
<td><table border="0" cellpadding="0" cellspacing="0" width="100%">
<tr class="ms-WPHeader">
<td align="left" class="ms-wpTdSpace"> </td><td title="Graduation Rates - My Visual WebPart" id="WebPartTitlectl00_m_g_08bc0677_b337_4b17_8729_6ca0b60b83e7" class="ms-WPHeaderTd"><h3 style="text-align:justify;" class="ms-standardheader ms-WPTitle"><nobr><span>Graduation Rates</span><span id="WebPartCaptionctl00_m_g_08bc0677_b337_4b17_8729_6ca0b60b83e7"></span></nobr></h3></td><td align="right" class="ms-WPHeaderTdMenu" onclick="OpenWebPartMenu('MSOMenu_WebPartMenu', this, 'WebPartctl00_m_g_08bc0677_b337_4b17_8729_6ca0b60b83e7','False'); TrapMenuClick(event); return false;"><span style="display:none;"></span><div class="ms-WPMenuDiv" onmouseout="this.className='ms-WPMenuDiv'" onmouseover="this.className='ms-WPMenuDivHover'"><a onclick="OpenWebPartMenuFromLink('MSOMenu_WebPartMenu', this, 'WebPartctl00_m_g_08bc0677_b337_4b17_8729_6ca0b60b83e7','False'); return false;" id="WebPartctl00_m_g_08bc0677_b337_4b17_8729_6ca0b60b83e7_MenuLink" onkeydown="WebPartMenuKeyboardClick(document.getElementById('WebPartctl00_m_g_08bc0677_b337_4b17_8729_6ca0b60b83e7_MenuLink'), 13, 40, event)" href="#" title="Graduation Rates Web Part Menu" class="ms-wpselectlink" onblur="UpdateWebPartMenuFocus(this, 'ms-wpselectlink', 'ms-WPEditText');" onfocus="UpdateWebPartMenuFocus(this, 'ms-wpselectlinkfocus', 'ms-WPEditTextVisible');" menuid="MSOMenu_WebPartMenu"><img class="ms-WPHeaderMenuImg" src="/_layouts/images/wpmenuarrow.png" alt="Graduation Rates Web Part Menu" style="border-width:0px;" /></a></div></td><td class="ms-WPHeaderTdSelection"><span class="ms-WPHeaderTdSelSpan"><input type="checkbox" id="SelectionCbxWebPartctl00_m_g_08bc0677_b337_4b17_8729_6ca0b60b83e7" class="ms-WPHeaderCbxHidden" title="Select or deselect Graduation Rates Web Part" onblur="this.className='ms-WPHeaderCbxHidden'" onfocus="this.className='ms-WPHeaderCbxVisible'" onkeyup="WpCbxKeyHandler(event);" onmouseup="WpCbxSelect(event); return false;" onclick="TrapMenuClick(event); return false;" /></span></td><td align="left" class="ms-wpTdSpace"> </td>
</tr>
UPDATE- WORKING CODE BELOW
The key was creating a custom data attribute as #Fil indicated and passing from the code behind and then accessing the $.cache. And passing the clientID of the reportviewer into the javascript function to get to the current instance of the webpart child controls.
<input type="hidden" id="<%= ASP_SSRS.ClientID %>_myDataState"
onchange="compareUnitValues(this.id, this.parentNode.id, '<%= ReportViewer1.ClientID %>', '<%= ASP_SSRS.ClientID %>', '<%= btnSendHiddenField.ClientID %>');" />
<script type ="text/javascript">
function compareUnitValues(elemt, parent, reportviewerID, value1, value2) {
var myDataUnit = $("#" + elemt),
parentObject = $("#" + parent),
reportviewerObject = $("#" + reportviewerID),
ssrs = $("#" + value1),
btnSend = $("#" + value2);
var myDataUnitValue = myDataUnit.val();
var myDataUnitJSON = jQuery.parseJSON(myDataUnitValue);
var currentmyDataUnit = myDataUnitJSON.currentUnit.objectId;
var sessioncurrentObjectId = document.getElementById('<%= hiddenCurrentObjectId.ClientID %>').value;
ssrs.val(myDataUnitValue);
var currentReportViewerParam = $("#" + reportviewerID).attr("data-report-param");
if (currentmyDataUnit != currentReportViewerParam) {
btnSend.trigger("click");
}
}
FROM CODE BEHIND CREATE THE CUSTOM DATA ATTRIBUTE
ReportViewer1.Attributes.Add("data-report-param", parsedObjectId)
If you have that property visible when the html renders (see if it does by viewing source on your browser), then you would be able to fetch it on the client end using JS.
You could reference the report viewer control either by assigning it a unique class name, or by using jQuery's ends with or contains selector:
$("[id*='ReportViewer1']").attr("attributeName"); - this is the contains selector
http://api.jquery.com/attribute-contains-selector/
http://api.jquery.com/attribute-ends-with-selector/
Is this what you are looking for?
UPDATE on the HTML5 data attribute question:
Just a cleaner way to store arbitrary data in the html (for more convenient access to Javascript). Here is a good article that explains it here
So, what you would do in practice is this: Imagine you want to add the report viewer's parameter (which for the sake of argument has a value of "42") as an attribute to a Panel control you have with an ID="Panel1". In code behind you would do
Panel1.Attributes.Add("data-report-param", "42");.
Because the Panel control is rendered as a <div> element, you will see something like this:
<div id="Panel1" data-report-param="42">
Finally you would be able to grab it from Javascript using one of the following two ways:
$("#Panel1").data("report-param");
$("#Panel1").attr("data-report-param");
UPDATE on retrieving the attribute
If they are on the same node, try this:
$.each($("[id*='ReportViewer1']"), function(index, value) {
if ($(value).is("[data-report-param]"))
{
alert($(value).attr("data-report-param"));
}
});
This will go through each element that contains "ReportViewer1" in its ID. Then for each item it will check if that element contains the "data-report-param" attribute. If so, alert the value. Hope this finally helps :)

Add Struts 2 select drop down list dynamically using JavaScript/JQuery

I have a student.jsp page that loads a select drop down list from the database Faculty
<s:select list="ftyList" name="fid" listKey="fid" listValue="name" label="Select a Faculty" />
Now, I've got to add more of the exact same drop down list when I click on Add button. For that I've got a div with Add button and my JavaScript code as below:
<div id="div">
<button onclick="addListFunction()">Add</button>
</div>
addDropDown.js:
function addListFunction() {
var d = document.getElementById("div");
d.innerHTML += "<p><s:select list='ftyList' name='fid' listKey='fid' listValue='name' label='Select a Faculty' /></p>";
}
The problem is that when I click on the 'Add' button it's only adding an empty space. When used firebug, I could see the Struts tag was being printed the same as above instead of HTML tags.
<s:select> is a struts tag which cannot be added directly from javascript and assumed to run server side.
You can use jQuery Clone method when Add button is clicked.
<s:select list="ftyList" name="fid" listKey="fid" listValue="name" cssClass="fidSelect" label="Select a Faculty" />
function addListFunction() {
$('.fidSelect').clone().insertAfter(".fidSelect");
}
You can try this uisng jQuery
function addListFunction() {
var optionList = [{"key":"1" , "value":"item1"},
{"key":"2" , "value":"item2"},
{"key":"3" , "value":"item3"},
{"key":"4" , "value":"item4"},
{"key":"5" , "value":"item5"},
{"key":"6" , "value":"item6"}];
var combo = $("<select>").attr("id", "inputAuto").attr("name", "selectTag");
$.each(optionList, function (j, el1) {
var opt = $("<option>").attr("value",el1.key).append(el1.value);
combo.append(opt);
});
$("#DivId").append(combo);
}
In this i have statically define the array of option (e.g. optionList). But you can make an ajax call for this.
The struts tags are only interpretet once by the server before the page is delivered. If you manipulate the dom afterwards with JavaScript you can't use JSP Tags.

Categories

Resources