Get value from jQuery in asp.net code nugget? - asp.net

How can I get the value from a select field (dropdownlist) into a "code nugget" using jQuery? I have seen this done, but can't find an example of it now.
I have two dropdownlists, and I want to get the selected values from them and concatenate it into an id parameter to send to an action method:
$.get('<%= Url.Action("GetTasks","Timesheet", new { id = [Concatenated value here] } %>'
How can I get the concatenated selected values from the two dropdownlists with jQuery?

You could try something like this:
var url = "<% Url.Action("GetTasks", "Timesheet", new { id = "{0}" }) %>";
var selected = $("#mySelect").val().join(",");
url = url.replace("{0}", selected);
$.get(url);

Related

Retrieve multiple value in one session

when i add to cart
i using Session["Cart"] = new List() { Id }; which is get the id pass from the query string
but when i preview on the cartview event i add 2/3 product, it only will show 1 column, which is the latest. why it will replace? my code look like. how should i do to make sure every time i add it will be display on the view cart page? if this code problem or my cart preview page have probelm?
Try this example ,
string[] a = new string[]{"a","b","c"};
Session["values"] = a;
And you can retrieve it like this.
string[] a = (string[])Session["values"]
using List
Session["test"] = yourList;
And you can retrieve it like this.
var list = (List<string>)Session["test"];

adding url to the hyperlink field in gridview

I have a dynamic grid view. I add column in page load.
I use this code for add Hyperlinkfield :
string[] url = new string[1];
url[0] = field.InternalName;
HyperLinkField link = new HyperLinkField();
link.HeaderText = field.Title;
link.DataNavigateUrlFields = url;
link.DataNavigateUrlFormatString = "{0}";
link.DataTextField = field.InternalName;
link.SortExpression = field.InternalName;
grid.Columns.Add(link);
my problem is : for example my url is "http://Test1.docx, http://Test1.docx".
I want navigateurl set "http://Test1.docx" .
If I am understanding correctly what the issue is. The field.InternalName field contains "http://Test1.docx, http://Test1.docx" to which you are assigning to a string array and you are trying to attempt to only get the first value before the comma.
In that case, you will need to split the string:
string[] urlSplit = field.InternalName.Split(',');
link.DataNavigateUrlFields = urlSplit[0];

Generating an action URL in JavaScript for ASP.NET MVC

I'm trying to redirect to another page by calling an action in controller with a specific parameter. I'm trying to use this line:
window.open('<%= Url.Action("Report", "Survey",
new { id = ' + selectedRow + ' } ) %>');
But I couldn't make it work; it gives the following error:
CS1012: Too many characters in character literal.
Can't I generate the action URL this was on the client side? Or do I have to make an Ajax call by supplying the parameter and get back the needed URL? This doesn't seem right, but I want to if it's the only way.
Is there an easier solution?
Remember that everything between <% and %> is interpreted as C# code, so what you're actually doing is trying to evaluate the following line of C#:
Url.Action("Report", "Survey", new { id = ' + selectedRow + ' } )
C# thinks the single-quotes are surrounding a character literal, hence the error message you're getting (character literals can only contain a single character in C#)
Perhaps you could generate the URL once in your page script - somewhere in your page HEAD, do this:
var actionUrl =
'<%= Url.Action("Report", "Survey", new { id = "PLACEHOLDER" } ) %>';
That'll give you a Javascript string containing the URL you need, but with PLACEHOLDER instead of the number. Then set up your click handlers as:
window.open(actionUrl.replace('PLACEHOLDER', selectedRow));
i.e. when the handler runs, you find the PLACEHOLDER value in your pre-calculated URL, and replace it with the selected row.
I usually declare a javascript variable in the section to hold the root of my website.
<%="<script type=\"text/javascript\">var rootPath = '"
+ Url.Content("~/") + "';</script>" %>
To solve your problem I would simply do
window.open(rootPath + "report/survey/" + selectedRow);
Could you do
window.open('/report/survey/' + selectedRow);
instead where selected row I assume is the id? The routing should pick this up fine.
or use getJSON
Perhaps you could use JSONResult instead. Wherever the window.open should be call a method instead i.e. OpenSurveyWindow(id);
then add some jquery similar to below
function OpenSurveyWindow(id){
$.getJSON("/report/survey/" + id, null, function(data) {
window.open(data);
});
}
now in your controller
public JsonResult Survey(int id)
{
return Json(GetMyUrlMethod(id));
}
That code isnt syntactically perfect but something along those lines should work
Just if someone is still looking for this. The controller action can have normal parameters or a model object with these fields. MVC will bind the valus automatically.
var url = '#Url.Action("Action", "Controller")';
$.post(url, {
YearId: $("#YearId").val(),
LeaveTypeId: $("#LeaveTypeId").val()
}, function (data) {
//Do what u like with result
});
You wont be able to do this, the URL.Action is a server side process so will parse before the clientside selectedRow is available. Israfel has the answer I would suggest.
If selectedRow is a client-side variable, it won't work. You have to use #Israfel implementation to link. This is because the server-side runs before the client-side variable even exists.
If selectedRow is a server-side variable within the view, change to this:
window.open('<%= Url.Action("Report", "Survey", new { id = selectedRow } ) %>');
This is because the id will infer the selectedRow variable type, or you could convert to string with ToString() method (as long as it's not null).
A way to do this that might be considered cleaner involves using the T4MVC T4 templates. You could then write the JavaScript inside your view like this:
var reportUrl = '<%= Url.JavaScriptReplacableUrl(MVC.Survey.Report())%>';
reportUrl = myUrl.replace('{' + MVC.Survey.ReportParams.id + '}', selectedRow);
window.open(reportUrl);
The advantage of this is that you get compile-time checking for the controller, action, and action parameter.
One more thing that can be done, no so clean i guess:
var url = "#Url.RouteUrl(new { area = string.Empty, controller = "Survey", action = "Report" })";
var fullUrl = url + '?id=' + selectedRow;
The easiest way is to declare a javascript variable than concate your parameter value to the link.
var url = '#Url.Action("Action","Controller")' + "/" + yourjavascriptvariable;
<a href='" + url + "'>

Dynamic data asp.net Query String parameter

Is there a way to define my own querystring parameter in Dynamic data rather then using something like
Edit.aspx?AccountID=1
I want to use something like this
Edit.aspx?id=1
I found a solution for this problem
I simply added this on the pageload method of my edit page template
string id = String.Empty;
if(Request.QueryString["id"] != null ){
id = Request.QueryString["id"].ToString();
DetailsDataSource.WhereParameters.Clear();
DetailsDataSource.WhereParameters.Add("AccountID", DbType.Int32, id);
}

getting client id of a control from variable

I want the client id of an asp.net textbox control(txtTest) in javascript.But the problem here is the control id comes from a variable as shown below
var testName = 'txtTest';
var testCntrl = document.getElementById('<%=' + testName + '.ClientID %>');
But its throwing
CS1012: Too many characters in
character literal
Can any one please help....
Try this:
document.getElementById('<%=txtTest.ClientID %>');
Or more along the lines of your original example:
var testName = '<%=txtTest.ClientID %>';
var testCntrl = document.getElementById(testName);
It appears from your example that you have managed to confuse yourself over what is server side and what is client side code.
<%= aspControlID.ClientID %> is a server side control, but you are trying to pass a clientside variable name to it. By the time testName is set equal to 'txtTest' its too late, you're already on the client.
There are a number of alternatives to get the server side ClientIDs as Rick Stahl discusses.
1) You can pre-load all the control IDs that you know you're going to need like this, they query them (he uses jquery) when you need their elements.
var ids = {
txtSymbol: "#<%= txtSymbol.ClientID %>",
PageContent: "#<%= PageContainer.ClientID %>"
}
This can also be written:
var txtSymbol = document.getElementById('<%= txtSymbol.ClientID %>');
var txtBlah = document.getElementById('<%= txtBlah.ClientID %>');
2) Or, he wrote a function that will get a control for you from the clientside
function $$(id, context) {
var el = $("#" + id, context);
if (el.length < 1)
el = $("[id$=_" + id + "]", context);
return el;
}
Be aware that there are some serious caveats. This relies on JQuery, so be sure to include that library and use it like this $$('myASPControlID').val('new val'); The catch is that if you have any controls that create other controls, like listviews, repeaters, gridviews etc. Then finding a single instance of a child control will take some strategy. In that situation, this tool will only get the first instance of a repeated control.
Still, the function provides a way to solve this problem by allowing you to specify a containing element in the second field.
EDIT
Hey L G, if you really need to pass your variable from the client side, then just add the second function and a link to the JQuery library. Then you can get your control with this simple code:
var testName = 'txtTest';
var testCntrl = $$(testName);
If it is C# code (which I assume, given the compilation error), you need to surround strings with " instead of '.
' is used for char values, that can contain only one character (or two if it is an escaped one, such as '\n').
But I don't really get the connection between the compilation error and the code, since the C# compiler should not bother about the javascript code...

Resources