I am not an expert in jQuery and I am trying to pass some variable values from C# to my function called on keyup and onclick events. So far I have something like this:
$('mydiv').bind('keyup click', function(event) {}
but what I need should be:
$('mydiv').bind('keyup click', function(event, UserId, ControlId) {}
, where UserId and ControlId are some ids I am getting in code behind from the query string. I am also using jQuery 1.6.4.
How can I do this, preferably without using hidden input fields?
Thank you.
Use on instead of bind
As of jQuery 1.7, the .on() method is the preferred method for attaching event handlers to a document.
Passing values from the server to the client with razor (if youre using asp.net mvc):
$('mydiv').on('keyup click', function(event, #UserId, #ControlId) {}
or if its webforms:
$('mydiv')
.on('keyup click', function(event, <%= UserId %>, <%= ControllId %>) {}
I would use data-attributes:
$('mydiv').data({ userId: <%= UserId %>, ControllId: <%= ControllId %> })
then you can access those data in the on click event:
$('mydiv').on('click', function(event) {
var userId = $(this).data('userId');
var ControlId = $(this).data('ControlId');
});
declare the variable as public in code behind
public string userId="abc";
Access it on client side
var uid='<%=userId %>';
$('mydiv').bind('keyup click', function(event, uid, ControlId) {}
A js file cannot directly access C# objects so you need to do something like below.
Even if you want to write complete jQuery code in your view file, you can still follow same approach.
So you can pass variables in some Model which is passed to View and once you have those variables in Model you can do something like below:
<script type="text/javascript">
var myList= #Html.Raw(Json.Encode(#Model.UsersList));
</script>
So now you have a json object which can be accessed by any individual js file as well with in same view file with the help of variable "myList".
Javascript scopes are not like scopes in other languages
so if you write
var UserId = 5;
var ControlId = 5;
$('mydiv').bind('keyup click', function(event)
{
alert( UserId );
});
it will work
check out http://jsfiddle.net/FgYTL/1/
Is my mydiv a class, id or a jQuery variable? Looks like you need to do
$('div.mydiv') or $('div#mydiv')
Related
I would like to pass an id parameter from this action in controller
public IActionResult BuildingDetail(int id)
{
return PartialView("_BuildingDetailsPartial", _buildingRepository.GetById(id));
}
into this load method in view to run AJAX.
#section Scripts{
<script type="text/javascript">
$(document).ready(function () {
$("#LoadBuildingDetail").click(function () {
$("#BuildingDetail").load("/employees/buildingdetail/id");
});
})
</script>}
I am new to jQuery, but I guess I need to store id vaule somehow before passing it into load function, so controller/action/parameter approach does not work. But atm I had no luck.
If you want to pass id to the controller via jquery load method, you can pass it directly into the load method as an object.
I assume you have the id's value somewhere on the page or you are hardcoding it in the view using razor syntax from your model.
In any case, try using something like this in your jquery
//passing id's value from the control on the page
$("#BuildingDetail").load("/employees/buildingdetail", { id: $("#Id").val() });
or
//passing id's value from the Model property
$("#BuildingDetail").load("/employees/buildingdetail", { id: #Model.Id });
Reference: jQuery load method
I am trying to access the script variable pic and assign it to another variable in C#, say hidden field hdn. The script below is also placed on the same code behind page for some reason. I can directly access the hidden field here. But how do I assign it value from the script variable?
<script type=\"text/javascript\">
$(document).ready(function() {
$.get('<%=completeURL%>',
function(d) {
$(d).find('entry').each(function(){
var $entry = $(this);
var pic = $entry.find('content').attr('src');
alert(pic);
});
});
});
</script>
There is no way to assign a C# variable by javascript.
You have to send that value from the client (where you JavaScript is running) to the Server, and assign it.
This is so called ajax request, just google it and you'll find millions of good examples of how to achieve that.
create a hidden filed and then set the value from javascript
<asp:hiddenfield id="hf_MyValue"
value="whatever"
runat="server"/>
How To Set value in javascript
//get value from hidden filed
var test= document.getElementById('<%= hf_MyValue.ClientID %>');
//set value in hidden filed
document.getElementById('<%= hfBrand.ClientID %>').value = "True";
Create a hidden variable like this,
<input type="hidden" id="hdnVariable" runat="server" />
Now try this code
<script type=\"text/javascript\">
$(document).ready(function() {
$.get('<%=completeURL%>',
function(d) {
$(d).find('entry').each(function(){
var $entry = $(this);
var pic = $entry.find('content').attr('src');
//assign value to server side hidden variable
$("#<%=hdnVariable.ClientID%>").val(pic);
});
});
});
</script>
Now you can access this hidden field from C# code like this
string pic=hdnVariable.Value;
I have a link like this
<a class="viewp" href="#">#data.name</a>
and I would like to call a jquery ajax this way
$(document).ready(function ()
{
$('.viewp').click(function (id)
{
var responseUrl="~/click?id="+id;
$.ajax(
{
type: "GET",
data:id,
url:responseUrl,
success:success
});
});
});
But I don't know how the id of the #data.name is passed into the jquery function.
If I replace the above link's href with href="~/click?id=#data.id"
then that is supposed to load the whole page not some specific region and clearly ajax doesn't work also.
[UPDATE]
By id I would mean the id primary key of my sql table and I am using webmatrix to code my simple web page. My database table looks like this create table x(id, name)
I haven't got what exactly you mean
if it is like
< a class="viewp" href="#" id="someId" >#data.name< /a>
if you want to get id of it
then
$(this).attr("id");
if you want to get text #data.name
then
$(this).text();
You can do something like this:
<a id="#data.id" class="viewp" href="#">#data.name</a>
And then in the function you can get the id:
$('.viewp').click(function()
{
var id = this.id
}
use $(this) to get the currently clicked a tag and then get the id attribute value of that.
$('.viewp').click(function(){
var id=$(this).attr("id");
var responseUrl="~/click?id="+id
//do your ajax call here
});
I have the following block of code in my header:
<script type="text/javascript">
$(document).ready(function () {
$('#target').readmytweet({
'color': 'black',
'search': 'from:' + <%= GetUserName() %>,
'user': <%= GetUserName() %>,
'width': 600,
'tweets': 10,
'speed': 25
});
})
</script>
protected string GetUsername()
{
return "somestring..";
}
However, I am getting an error message:
The Controls collection cannot be modified because the control
contains code blocks (i.e. <% ... %>).
Does anyone know how I can pass a C# variable from my code behind into this jQuery function without getting that error?
Thanks in advance
For a dynamic string:
That seems like it would work, try wrapping the code blocks with quotes, as such:
'<%= GetUserName() %>'
also you may have to use a this statement to access that method:
'<%= this.GetUserName() %>'
For a static string:
Declare your string as a public string in your aspx page:
public string UserName = "somestring..";
and access it via:
var userName = <%=this.UserName%>;
This is a well-known problem when trying to add controls to a page that contains code blocks.
A simple workaround is to use data binding expressions instead, i.e., to use <%# ... %> instead of <%= ... %>. Note that you will have to call this.DataBind(); in your Page_Load event for this to work.
(BTW, remember that the code you insert in JavaScript will need to be properly quoted.)
Accessing a server-side c# variable/property within an .aspx page.
<script type="text/javascript">
<% string username = Class.PropertName; %>
var jsUsername = '<%: username %>';
</script>
I have a list of Payees in a drop down box on my form. I would like to populate a different drop down, based on the selected item of the Payee drop down, without post backs and all that.
So, I created a method in my controller that does the work:
private JsonResult GetCategories(int payeeId)
{
List<CategoryDto> cats = Services.CategoryServices.GetCategoriesByPayeeId(payeeId);
List<SelectListItem> items = new List<SelectListItem>();
foreach(var cat in cats)
{
items.Add(new SelectListItem {Text = cat.Description, Value = cat.CategoryId.ToString()});
}
return Json(items);
}
Now, I am unsure what to add to my view to get this to work.
At the moment, all I have is this:
<% using (Html.BeginForm())
{%>
<p>
<%=Html.DropDownList("SelectedAccountId", Model.Accounts, "Select One..", null) %>
</p>
<p>
<%=Html.DropDownList("SelectedPayeeId", Model.Payees, "Select One...", null) %>
</p>
<input type="submit" value="Save" />
<%
}%>
they populate fine... so when the user selects the SelectedPayeeId drop down, it should then populate a new (Yet to be created?) drop down which holds categories, based on the SelectedPayeeId.
So, I think I need to create a JQuery function (Never done JQuery.. so not even sure where it goes) which monitors the Payee drop down for an onChange event? And then call the method I created above. Does this sound right, and if so, can you guide me in how to achieve this?
Your reasoning so far is totally sound. First you are going to want to include the jquery library in your View / Master. You can download a copy of jquery from http://jquery.com/. Add the file to you project and include a <script src="/path/to/jquery.js"> to the <head> of your document. You are going to want to add another dropdown to your View (and probably another property to your model). We'll call this 'SelectedCategoryId:'
<%=Html.DropDownList("SelectedCategoryId", null, "Select One...", new { style = "display:none;"}) %>
We've set the style of this Drop Down to not be visible initially because there is nothing to select inside of it. We'll show it later after we generate some content for it. Now, somewhere on your page you will want to include a <script> block that will look something like this:
$(document).ready(function() { $('#SelectedPayeeId').change(function() {
$.ajax({
type: 'POST',
url: urlToYourControllerAction,
data: { payeeId: $(this).val() },
success: function(data) {
var markup = '';
for (var x = 0; x < data.length; x++ ) {
markup += '<option value="' + data[x].Value + '">'+data[x].Text+'</option>';
}
$('#SelectedCategoryId').html(markup).show();
}
}); }); });
This code binds the anonymous function written above to the DOM element with the ID of 'SelectedPayeeId' (in this case your dropdown). The function performs an AJAX call to the url of your method. When it receives the results of the request (your JSON you returned) we iterate over the array and build a string of the html we want to inject into our document. Finally we insert the html into the 'SelectedCategoryId' element, and change the style of the element so it is visible to the user.
Note that I haven't run this code, but it should be (almost) what you need. jQuery's documentation is available at http://docs.jquery.com/Main_Page and the functions I used above are referenced here:
.ready()
.change()
jQuery.ajax()
.html()
.show()
You'd need to make the GetCategories as a public method as it would correspond to an action handler in your controller.
Your jquery code can look like:
<script type="text/javascript">
$(function() {
$('#SelectedPayeeId').change(function() {
$.get('<%= Url.Action("GetCategories", "YourControllerName") %>',
{payeeId: $(this).val()},
function(data) {
populateSelectWith($("#Category"), data);
});
});
//Place populateSelectWith method here
});
</script>
The populateSelectWith can fill your dropdown with data like:
function populateSelectWith($select, data) {
$select.html('');
$select.append($('<option></option>').val('').html("MYDEFAULT VALUE"));
for (var index = 0; index < data.length; index++) {
var option = data[index];
$select.append($('<option></option>').html(option));
}
}
I have not tested this code, but I am hoping it runs okay.
You can find syntax for the jquery ajax get here
Since you are not posting any data to the server, you can might as well decorate your controller action with a [HttpGet] attribute