Use the controller name from Javascript in the Url.Action - javascript

I am retrieving controller name from a javascript function as a string, and need to pass controller name in Url.Action. Any suggestion would be helpful.
var controllerName = "MyController";
var id=1;
#Url.Action("LoadAction","'"+ controllerName +"'")?id=' + id
// Here i am unable to pass controllerName, defined using javascript.
Thanks.

If you want to send data from a js script to a C# controller, then you can use a Jquery-ajax call instead of #Url.Action, if I'm not mistaken, you can't even use #Url.Action on a js source code.
const sendId = () => {
const controllerName = 'MyController';
const id = 1;
$.ajax({
contentType: 'application/json',
data: { myId: id },
url: `${controllerName}/methodName`, //template string
type: 'POST',
success: function (data) {
//...
},
failed: function () {
//...
}
});
}

Related

Parsing array multidimension from ajax to controller in codeigniter?

I have a dynamic table and i want to send in controller by ajax. I have code ajax like this :
$(".save").click(function(e){
var items = new Array();
$("#list-item tr.item").each(function () {
$this = $(this)
var ref_item_id = $this.find("#ref_item_id").val();
var ref_pic_id = $this.find("#ref_pic_id").val();
var price= $this.find("#price").val();
var qty= $this.find("#qty").val();
items.push({ ref_item_id : ref_item_id, ref_pic_id : ref_pic_id, price: price, qty : qty});
});
$.ajax({
type: "POST",
contentType: "application/json; charset=utf-8",
url: '<?php echo base_url("transac/save")?>',
dataType: "json",
data: JSON.stringify({'items': items }),
success: function (data) {
var obj = $.parseJSON(data);
alert(obj.lenth);
},
error: function (result) { alert(result); }
});
})
now, how get data in controller and save in table database. My Controller like this :
public function penjualan_save(){
$items = $this->input->post("items");
// next code ???
}
I hope you can help me. Thanks
first thing, your don't need JSON.stringify({'items': items }), just use:
data: {'items': items },
and in your controller, just create a model and pass your post data into it, for example:
public function penjualan_save(){
$items = $this->input->post("items");
$this->load->model('model_name');
$this->model_name->insert($items);
}
then you need to define a function for your model, like this:
public function insert($data)
{
// if you didn't call database library in autoload.php
$this->load->database();
$this->db->insert_batch('mytable', $data);
}

Passing Javascript variable to Java Controller (Spring-boot)

I'm new to this, so after I have read some solution about this but still not get it.
I have a var id = [] and want to pass it to my controller to delete it from database (SQL server)
My JavaScript
$('#deleteButton').click( function () {
var id = [];
var length = table.rows('.selected').data().length;
for(var i = 0; i < length; i++){
id.push(table.rows('.selected').data()[i][0])
}
$.ajax({
url: "",
//idk to put what into this url
//I think to put an url to show my var but i getting 404 and
//maybe im missing something in controller
//my url to access the project is: localhost:8084
method: 'POST',
data: {
idList: id
},
success: function (data) {
console.log(id);
}
});
console.log(id);
table.rows('.selected').remove().draw( false );
} );
My java controller
#Controller
#ComponentScans(value = { #ComponentScan })
public class CandidateController {
#Autowired
CandidateServiceImp candidateService;
//localhost:8084/manageCandidates is where i show datatable
//and var id = [] is getting from this table
#RequestMapping(value = { "/manageCandidates"})
public String manageCandidatesPage(Model model) {
model.addAttribute("listCandidates",candidateService.getAllCandidates());
return "manageCandidates";
}
}
Please instruct me to get var = id[] in controller
Thanks alot
There are three processes.
Add content-type: application/json in client-side ajax.
And enclose the data in JSON.stringify.
If the server-side Model is properly structured, add #RequestBody before the Model.
Use JSON:
Controller :
#RequestMapping(value = "/manageCandidates", method = RequestMethod.DELETE)
public #ResponseBody String manageCandidatesPage(HttpServletRequest request,#RequestBody String idjson) throws Exception
System.out.println("id"+idjson);
}
Ajax:- data: JSON.stringify(id),
$.ajax({
url: "",
type: "",
async: false,
processData: false,
contentType: "application/json; charset=utf-8",
data: JSON.stringify(id),
success: function(data) {
response = data;
}
});

Retrieving event and htmlInput element from a foreach using javascript or jquery

I managed to retrieve a dynamic element ID from inside a foreach and send it to a controller this way:
#using (Html.BeginForm("DeleteConfirmed", "Gifts", FormMethod.Post, new { #class = "form-content", id = "formDiv" }))
{
foreach (var item in Model.productList)
{
<input type="button" value="Delete" onclick="DeleteButtonClicked(this)" data-assigned-id="#item.ID" />
}
}
and here's the relevant script, pointing to the controller's ActionResult method in charge for item deletion:
function DeleteButtonClicked(elem) {
var itemID = $(elem).data('assigned-id');
if (confirm('sure?')) {
window.location.href = "/Gifts/DeleteConfirmed/" + itemID;
}}
Now, this works just fine, as itemID is correctly retrieved.
As I would like to add a #Html.AntiForgeryToken() to the form, the idea is to change the MVC controller's Actionmethod into a JsonResult adding a little Ajax to the script, allowing me to pass both itemID and token.
Something like:
function DeleteButtonClicked(elem) {
event.preventDefault();
var form = $('#formDiv');
var token = $('input[name="__RequestVerificationToken"]', form).val();
var itemID = $(elem).data('assigned-id');
if (confirm('sure?')) {
$.ajax({
type: 'POST',
datatype: 'json',
url: '#Url.Action("DeleteConfirmed", "Gifts")',
data: {
__RequestVerificationToken: token,
id: itemID
},
cache: false,
success: function (data) { window.location.href = "/Gifts/UserProfile?userID=" + data; },
error: function (data) { window.location.href = '#Url.Action("InternalServerError", "Error")'; }
});
}
dynamic }Some
but I have no idea on how to add the 'event' to the element (this => elem) in <input type="button" value="Delete" onclick="DeleteButtonClicked(this)" data-assigned-id="#item.ID" /> that I am using to identify the item inside the foreach loop, in order to pass it to the script.
Above script obviously fails as there's no 'event' (provided this would end to be the only mistake, which I'm not sure at all).
Some help is needed. Thanks in advance for your time and consideration.
What you want to do is use jQuery to create an event handler:
$('input[type="button"]').on('click', function(event) {
event.preventDefault();
var form = $('#formDiv');
var token = $('input[name="__RequestVerificationToken"]', form).val();
var itemID = $(this).data('assigned-id');
if (confirm('sure?')) {
$.ajax({
type: 'POST',
datatype: 'json',
url: '#Url.Action("DeleteConfirmed", "Gifts")',
data: {
__RequestVerificationToken: token,
id: itemID
},
cache: false,
success: function (data) { window.location.href = "/Gifts/UserProfile?userID=" + data; },
error: function (data) { window.location.href = '#Url.Action("InternalServerError", "Error")'; }
});
}
});
Just make sure you render this script after your buttons are rendered. Preferably using the $(document).onReady technique.
Try the 'on' event handler attachment (http://api.jquery.com/on/). The outer function is shorthand for DOM ready.
$(function() {
$('.some-container').on('click', '.delete-btn', DeleteButtonClicked);
})

Passing an array of Javascript classes to a MVC controller?

I am trying to pass an array of services to my controller.
I've tried a bunch of different ways to get it work, serializing the data before going to controller, serializing each service, only thing that seems to work is changing the controller parameter to string and serializing array, then using JsonConvert, but I'd rather not do that.
With the specified code, I am getting the correct number of items in the List, but they all contain a service id with an empty guild, and service provider id is null.
Any ideas?
Javascript
function ServiceItem() {
this.ServiceProviderID = 'all';
this.ServiceID = '';
}
var selecteditems= (function () {
var services = new Array();
return {
all: function() {
return services;
},
add: function(service) {
services.push(service);
}
};
})();
var reserved = [];
$.each(selecteditems.all(), function(index, item){
reserved.push({ ServiceID: item.ServiceID, ServiceProviderID: item.ServiceProviderID});
});
getData('Controller/GetMethod', { items: reserved }, function(result) {
});
var getData = function (actionurl, da, done) {
$.ajax({
type: "GET",
url: actionurl,
data: da,
dataType: "json",
async: true,
success: function (d) {
if (typeof (done) == 'function') {
var str = JSON.stringify(d);
done(JSON.parse(str));
}
}
});
};
Controller
public JsonResult GetMethod(List<CustomObject> items)
{
}
Custom Object
public class CustomObject
{
public Guid ServiceID {get;set;}
public Guid? ServiceProviderID {get;set;}
}
Set the content-type and use POST instead of GET (as it is a list of complex type objects). mark your action with HttpPost attribute too.
See if this works:-
$.ajax({
type: "POST",
url: actionurl,
data: JSON.stringify(da),
dataType: "json",
contentType: 'application/json',
async: true,
success: function (d) {
if (typeof (done) == 'function') {
var str = JSON.stringify(d);
done(JSON.parse(str));
}
}
});

Javascript url action in razor view

I have a javascript method onRowSelected wchich gets rowid. How to pass the rowid in certain action of a controller with HttpGet?
function onRowSelected(rowid, status) {
alert('This row has id: ' + rowid);
//url: #Action.Url("Action","Controller")
//post:"GET"
// Something like this?
}
If your controller action expects an id query string parameter:
var url = '#Url.Action("Action", "Controller")?id=' + rowid;
or if you want to pass it as part of the route you could use replace:
var url = '#Url.Action("Action", "Controller", new { id = "_id_" })'
.replace('_id_', rowid);
yet another possibility if you are going to send an AJAX request is to pass it as part of the POST body:
$.ajax({
url: '#Url.Action("Action", "Controller")',
type: 'POST',
data: { id: rowid },
success: function(result) {
}
});
or as a query string parameter if you are using GET:
$.ajax({
url: '#Url.Action("Action", "Controller")',
type: 'GET',
data: { id: rowid },
success: function(result) {
}
});
All those suppose that your controller action takes an id parameter of course:
public ActionResult Action(string id)
{
...
}
So as you can see many ways to achieve the same goal.
The method by Darin will work fine and perfectly.
I would suggest one more way for Razor view to use model value using #Html.actionlink in jsp
var URLvalue='#Html.ActionLink("UserString", "action", new { routeValueName1 = "__value1__", routeValueName2="__value2__" }, htmlAttributes: new { #class = "btn btn-default", #role = "button" })'
.replace('__value1__', Model.somevalue).replace('__value2__', Model.somevalue);
you can use URLvalue where ever you want to in jsp or jquery.

Categories

Resources