passing id to ajax call - c#

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
});

Related

Pass parameter to jQuery load function in ASP.NET Core

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

Transform Querystring to RouteValue in Razor View

I'm stuck with a very basic detail in a view.
I want to be able to let the user filter the results in the Index view.
To do this I've created a dropdown list, which gets populated thourgh my viewmodel:
#using (Html.BeginForm("Index", "Captains", FormMethod.Get)) {
<div class="row">
<div class="dropdown">
#Html.DropDownList("Name", new SelectList(Model.SomeProperty), new { id = "FilterList" })
</div>
</div>
#* ... *#
}
Additionally I have a small jQuery snippet to submit the form on the change event:
$('#FilterList').on('change', function () {
var form = $(this).parents('form');
form.submit();
});
The route I have created for this looks like this:
routes.MapRoute(
name: "IndexFilter",
url: "{controller}/{action}/{Name}",
defaults: new { Name = UrlParameter.Optional}
);
After the submit event I get redirected to the url /Index?Name=ChosenValue
This is filtering totally correct. However I'd like to get rid of the querystring and transform the route to /Index/ChosenValue.
Note: "Name", "ChosenValue" & "SomeProperty" are just dummy replacements for the actual property names.
Instead of submitting the form, you can concatenate /Captains/Index/ with the selected value of the dropdown and redirect to the url using window.location.href as below
$('#FilterList').on('change', function () {
window.location.href = '/Captains/Index/' + $(this).val();
});
I think you're looking for the wrong routing behavior out of a form submit. The type of route resolution that you're hoping to see really only happens on the server side, where the MVC routing knows all about the available route definitions. But the form submission process that happens in the browser only knows about form inputs and their values. It doesn't know that "Name" is a special route parameter... it just tacks on all the form values as querystring parameters.
So if you want to send the browser to /Index/ChosenValue, but you don't want to construct the URL from scratch on the client, you need to construct the URL on the server when the view is rendering. You could take this approach:
<div class="row">
<div class="dropdown">
#Html.DropDownList("Name", new SelectList(Model.SomeProperty),
new {
id = "FilterList",
data_redirect_url = #Url.Action("Index", "Captains", new { Name = "DUMMY_PLACEHOLDER" })
})
</div>
</div>
Above you're setting the URL with a dummy "Name" value that you can replace later, then you'll do the replacement with the selection and redirect in javascript:
$('#FilterList').on('change', function () {
var redirectUrl = $(this).data('redirect-url');
window.location.href = redirectUrl.replace("DUMMY_PLACEHOLDER", $(this).val());
});
If you are wanting to drop the query string off the url because it looks weird, then change your FormMethod.Post.
However, to really answer your question, I've tried the following successfully (Note: this might be considered a hack by some)
In short: update the action url on the form element when the list changes, client side.
$('#FilterList').on('change', function () {
var form = $(this).parents('form');
var originalActionUrl = form.attr("action");
var newActionUrl = originalActionUrl + "/" + $(this).val();
form.attr("action", newActionUrl);
console.log(form.attr("action"));
form.submit();
});
You will need to change your controller's signature to match whatever optional param value you specify in your route config. In your example, "Name".

Unable to send back data to action in MVC controller from javascript

I use jquery to load rows into a table. Each row contains an Id.
row = '<tr><td><button type="button" class="edit-form btn btn-default" data-form-id="' + value[0].id + '"></button></td></tr>';
tbody.append(row);
On click of a button, I need this Id to be sent back to an action in the controller, which would then redirect to a new view with this Id. On the new page, I would use this Id in a javascript function, which would then load details pertaining to this id using jQuery ajax.
I am not able to acheive this. I tried several things
Tried creating html action link using javascript which did not work
Used ajax to send data(id) to the action, but the action ended up returning the html of the new view as the response instead of redirecting
I've gone through several other Stackoverflow question related to this and have tried all of them. Nothing seems to work. Please suggest how i should tackle this problem. Any suggestions would be appreciated. I have sent data to other actions in the controller, but now my problem is that, I need this Id to go to the action and it should redirect me to a new page with this info available on that page
I have pasted the Code Below for the things I have tried.
$.each(this.data, function (key, value) {
var row = '<button type="button" class="edit-form btn btn-default" data-form-id="' + value[0].id + '"><span class="glyphicon glyphicon-eye-open"></span></button></td></tr>';
tbody.append(row);
});
On click of this button I call the following code in my javascript
openEditForm: function (evt) {
var formId = $(evt.currentTarget).data("formId");
$.ajax({
url: '/Home/Test',
type: "POST",
dataType: "json",
data: JSON.stringify({ formId: formId }),
contentType: "application/json; charset=utf-8;",
success: function (response) {
},
error: function (xhr, ajaxOptions, thrownError) {
}
});
}
In my Controller I have an action named Test which does the following
public ActionResult Test(string formId)
{
ViewBag.Title = "Testing Page ";
ViewBag.Message = "Testing Page" + formId + "hi";
return View();
}
What I want is that the action receive this formId and redirect it to a view called Test.cshtml. I need that view to have the formId info in it, so that I can use javascript on that page to make ajax calls to retreive the form info.
Used ajax to send data(id) to the action, but the action ended up returning the html of
the new view as the response instead of redirecting
By Above Line You Mean to Say that You want Data to Be posted to action ,and Action1 will call another Action where it will use That Returned ID...
So if this is The Case then Why are You using Ajax?
function myfunction()
{
var formId = $(evt.currentTarget).data("formId");
// window.location = "ActionNameHere?formId" + formId;
// foryour Case
window.location="Test?formId="+formId;
}
The Above code will Redirect you to
public ActionResult Test(string formId)
{
ViewBag.Title = "Testing Page ";
ViewBag.Message = "Testing Page" + formId + "hi";
return View();
}
From here you will have your New Page with Id in it...
The best way to initiate an HTTP request is with
document.loacation.href.replace('URL')
I would do:
option a) create a form element with an hidden field, populate it when the user clicks on the button and then submit the form to your action
<form method="post" action="/yourController/yourAction" id="frmAction">
<input type="hidden" name="parameterYouExpectinYourAction" value="" id="hdnField" />
</form>
<script>
$(".btn").on("click", function() {
$("#hdnField").val($(this).data("form-id"));
$("#frmAction").submit();
});
</script>
option b) create a normal link instead of a button like
'<a href="/controller/youraction?yourParam=' + value[0].id + '" >link</a>'
Is not the cleanest way, but could help you to make it work of figure out how to get it done in other ways (I hope).
The simplest way I see is simply an event on your button with a redirect to the URL with the ID.
$('button').on('click', function () {
window.location = 'http://yourURL' + '/' + $(this).attr('data-form-id');
});
Just modify it following your needs of course (Html.Action(...), $.post(...), ...).
Once inside your controller you can use return RedirectToAction(...) combined with the ID submitted to redirect the user to your second view.

Pass code behind variable value to jQuery function

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')

Asp.net MVC populate a list box with JQuery?

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

Categories