Passing variable from view to controller ajax - javascript

I am trying to get the id of a clicked button and then send that buttonId to the variable categoryId in the action AddItem of the controller ItemController using ajax but I am relatively new to ajax and am not sure where I am going wrong.
html code in view:
<button id="1" onclick=" buttonClicked(this.id)">button1</button>
javascript code in view that gets the id of the button clicked:
function buttonClicked(buttonId) {
$.ajax({
url: '<%: Url.Action("ItemController, AddItem")%>',
data: { 'id': buttonId },
type: "POST",
cache: false,
});
}
Controller code:
[HttpPost]
public ActionResult AddItem(int buttonId)
{
var categoyId = Convert.ToString(buttonId);
return View();
}

Related

Passing parameters in Ajax post back in MVC

I am trying to pass ID parameter from a view to a controller on a click delete link available on a selected row.
Simplified View Layout
#using (Html.BeginForm("#", "Schedule", FormMethod.Post, htmlAttributes: new { #class = "floating-labels" }))
{
#Html.AntiForgeryToken()
Delete
}
JavaScript
<script type="text/javascript">
function DeleteSchedule(id) {
if (confirm('Are you sure you want to delete this Schedule?')) {
$.ajax({
type: "POST",
url: '#Url.Action("Delete", "Schedule", new { id = "id" })',
contentType: "application/json",
data: { id },
async: true,
cache: false,
success: function (result) { success(result); }
});
}
return false;
}
function success(result) {
$("#ScheduleList").html(result);
}
</script>
Controller
namespace Controllers
{
public class ScheduleController
{
[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult Delete(int id)
{
//do stuff
}
}
}
But on the click of a delete link I get below error and code does not hit controller action.
I am not able to figure out what mistake I am making...
Here is my locally tested implementation that is working.
ScheduleController class:
public class ScheduleController : Controller
{
[HttpPost]
[ValidateAntiForgeryToken]
public IActionResult Delete(int id)
{
return Ok(id);
}
}
Page that sends the post request:
#Html.AntiForgeryToken()
Delete
<div id="ScheduleList"></div>
<script>
function DeleteSchedule(id) {
if (confirm('Are you sure you want to delete this Schedule?')) {
var uri = '/Schedule/Delete?id=' + id;
var tokenElement = document.getElementsByName('__RequestVerificationToken')[0];
var data = {
__RequestVerificationToken: tokenElement.value
}
$.ajax({
type: "POST",
url: uri,
data: data,
success: function (result) {
success(result);
}
});
}
return false;
}
function success(result) {
$("#ScheduleList").html(result);
}
</script>
The page does nothing but render the html, and the javascript handles the actual Ajax post. What I believe you were missing is the Validation token in your request.
It is because you are not actullay posting the form pass it correctly and add _token in the ajax data list and value for that token will come from #Html.AntiforgeryToken()
reading the error the request is most probably send correctly and there is an internal server error as mentioned in the 500 respond so please check the code that is inside the controller
Try this, you are accesing a javascript variable on c# code, and you cant do that.
If correct, please mark as answer.
function DeleteSchedule(id) {
if (confirm('Are you sure you want to delete this Schedule?')) {
var url = '#Url.Action("Delete", "Schedule")?id=' + id;
$.ajax({
type: "POST",
url: url,
contentType: "application/json",
data: { id },
async: true,
cache: false,
success: function (result) { success(result); }
});
}
return false;
}
I think none of the answers above solve the issue. First of all I would replace your target url:
url: '#Url.Action("Delete", "Schedule", new { id = "id" })',
with
url: '#Url.Action("Delete", "Schedule", new { id = actualIdVariable })',
(replace "id" with the actual id variable from the model you're passing to the view).
Note how your browser response is telling you that the url you're posting to is Schedule/Delete/id. That said, I'm not sure you even need the routeValues in this case (the new { id = ...} parameter). this is a POST action, and action parameters wouldn't come from route unless specified by by attribute routing (i.e. [Route("~/Schedule/Delete/{id}")] attribute on your action).
I think your post action is failing because it is trying to parse the "id" string as an int.
Second, I would change the data property of the ajax call and include the anti forgery token. Just because the anchor element you're binding the click event to, is inside the form with #Html.AntiforgeryToken() doesn't mean the generated token will be posted in the ajax request. You're not actually submitting/posting the form, you're just clicking a button.
it should be something like
data: {
'id': id,
'__RequestVerificationToken': $('[name="__RequestVerificationToken"]').val()
}
try this, it solve the error on routing (different url Action) and the parameter on the controller:
JavaScript
<script type="text/javascript">
function DeleteSchedule(id) {
if (confirm('Are you sure you want to delete this Schedule?')) {
$.ajax({
type: "POST",
url: '#Url.Action("Delete", "Schedule")',
data: "id=" + id ,
async: true,
cache: false,
success: function (result) { success(result); }
});
}
return false;
}
function success(result) {
$("#ScheduleList").html(result);
}
</script>
Controller:
[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult Delete(string id)
{
//do stuff
}
Nicola.

Cannot pass ViewBag value via AJAX post

I use checkboxes in an MVC5 Razor View and retrieve the checkbox values from Controller successfully by using ViewBag as shown below:
Controller:
public ActionResult Create()
{
ViewBag.RolesList = new SelectList(
this.RoleManager.Roles.ToList(), "Id", "Name");
return PartialView("_Create");
}
View:
#model Identity.ApplicationGroup
#foreach (var item in (SelectList)ViewBag.RolesList)
{
<div class="checkbox">
<label>
<input type="checkbox" name="#item" value="#item.Text">
#item.Text
</label>
</div>
}
However, I cannot pass the checkbox values to the Controller via AJAX as shown below while all of the other parameters are posted without any problem. So, how can I post them as the model values?
View:
function insert(event) {
var formdata = $('#frmCreate').serialize();
$.ajax({
type: "POST",
url: '#Url.Action("Insert", "GroupsAdmin")',
cache: false,
dataType: "json",
data: formdata
});
};
Controller:
[HttpPost]
[ValidateAntiForgeryToken]
public async Task<ActionResult> Insert([Bind(Exclude = null)] ApplicationGroup
applicationgroup, params string[] selectedRoles)
{
...
}

call an Asp Action from javascript

I have a table that will use is populated by javascript when another table option is clicked. All of this works no problem, when I add the delete button to the table the onClick event fires but this isn't ever called in asp.net.
function DeleteLink(id) {
$.ajax({
url: '/PublicPages/LinkDelete/',
data:{ id:id }
});
}
please tell me where I've gone wrong.
I have tried
function DeleteLink(id) {
$.ajax({
url: '/PublicPages/LinkDelete/' + id
}
as well
UPDATE:
[HttpPost]
public async Task<IActionResult> LinkDelete(Guid id)
{
var pageId = _linkDataProvider.FindById(id).PublicPage.Id;
_linkDataProvider.Delete(id);
var page = await _pageDataProvider.FindById(pageId);
var viewModel = _pageDataProvider.ConvertToViewModel(page);
return View("Details", viewModel);
}
UPDATE2
app.UseMvc(routes =>
{
routes.MapRoute(
name: "default",
template: "{controller=Flooring}/{action=Index}/{id?}");
});
You should specify http method in ajax settings. Try to change your javascript like below:
function DeleteLink(id) {
$.ajax({
type = 'POST',
url: '/PublicPages/LinkDelete/' + id
});
}
Update
If you prefer to use data:{ id:id } then you would need to create a model class:
public class DeleteModel
{
public Guid Id{get;set;}
}
[HttpPost]
public async Task<IActionResult> LinkDelete([FromBody]DeleteModel model)
....

Pass json data from Google Maps to MVC controller with AJAX

I want to store data about addresses and coordinates of markers on map, so I'm creating button in Infowindow which will redirect me to form on another view (also with another controller). I want this form to be already filled with data about coordinates and address. I have function called on button click with AJAX code in it to send JSON data to method in controller. Problem is that after clicking on button controller method isn't called (although function call works properly while debugging). I've been searching a lot for a solution, but I really don't know what did I do wrong.
Call to addMarker:
google.maps.event.addListener(marker, 'click', function (event) {
if(infowindow) infowindow.close();
infowindow = new google.maps.InfoWindow({content: data});
infowindow.open(map, marker);
var buttonAdd = document.getElementById('addButton');
buttonAdd.onclick = function() {
addMarker(event.latLng, address);
}
});
JS function with AJAX:
function addMarker(location, fulladdress) {
var data = JSON.stringify(fulladdress + location) //it's ok, i checked with firebug
$.ajax({
type: "POST",
url: "Incidents/Create",
dataType: "json",
contentType: "application/json; charset=utf-8",
data: data
})
}
Controller:
public class IncidentsController : Controller
{
//some code
[HttpPost]
public ActionResult Create(string JsonStr)
{
return View();
}
//some code
}
For now I'm just trying to get to another view without doing anything with recieved data, but it's not working. There's definetely something wrong with ajax or controller. I'm new to MVC, JS and AJAX, so please forgive me if it's something stupid. Thanks in advance.
TL;DR - Clicking on button should result in recieving another view with partially filled (with address and coordinates) form.
Found the problem.
You are using dataType: "json". If you want to post JSON in MVC then you need to create appropriate model with the same format that you are going to post.
Take a look at below example.
Controller :
public class JsonPostExampleController : Controller
{
[HttpPost]
public ActionResult JsonPost(JsonModel data)
{
return View();
}
}
Javascript :
$.ajax({
type: "POST",
url: "JsonPostExample/JsonPost",
dataType: 'json',
data: { 'name': 'ravi' },
success: function (data) { }
});
Model :
public class JsonModel
{
public string name { get; set; }
}
Now as per your requirement, we can not use dataType: "json" as you can't create model according to google's response format for fulladdress and location.
So you need to use dataType: "text" and for that you only need to modify your javascript.
Update your javascript block with below :
function addMarker(location, fulladdress) {
var data = JSON.stringify(fulladdress) + JSON.stringify(location)
$.ajax({
type: "POST",
url: "Incidents/Create",
dataType: "text",
data: { JsonStr : data }
});
}
and your controller code remains same as :
public class IncidentsController : Controller
{
//some code
[HttpPost]
public ActionResult Create(string JsonStr)
{
return View();
}
//some code
}
now you should be able to get your data in string format at server side. If you want JSON server side then you can parse the string.

Calling ActionResult method from the View using js

So I am calling my action result method using this:
var url= "/Example/Controler/1/Action";
$("<form action='"+url+"'></form>").submit();
But the action Method is not called...
I have also tried this
$.post(url, function (data) {});
And this works, we call the controller, but then the page doesn't refresh...
My action method looks like this:
public ActionResult DoStuff(int Id)
{
.....
return RedirectToAction("index", new { Id });
}
You can use Ajax function as follows :
$.ajax({
url: "/Controler/Action",
data: { 'Id': groupId },
type: 'GET',
success: function (result) {
//do the necessary updations
},
error: function (result) {
}
});
You can also try form submission as follows :
#using (Html.BeginForm("Action", "Controller", FormMethod.GET))
{
// do your html
<input type="submit" value="save"/>
}

Categories

Resources