How to call a controller method from Javascript - asp.net

I am displaying a bunch of movies in a table, I am eventually deleting each movie through Javascript which hides the div.
I now want to delete the movie from the database as well, so what is the best way to call the controller method from the Javascript?

Have an HTTPPost action method to delete in your movie controller
[HttpPost]
public ActionResult Delete(int id)
{
try
{
repo.DeleteMovie(id);
return "deleted"
}
catch(Exception ex)
{
//Log errror
}
return "failed";
}
And in your View,
Delete Avengers
Delete Iron Man
<script type="text/javascript">
$(function(){
$(".movie").click(function(e){
e.preventDefault();
$.post("#Url.Action("Delete","Movie")", { id : $(this).data("movieId")} ,function(data){
alert(data);
});
});
});
</script>

Depending on your code it could be as simple as:
$.post("/controller/method/" + id);

Try this: (Using jQuery Ajax)
$("#DeleteButtonID").on("click", function() {
$.ajax(
{
type: "POST",
page: 1,
rp: 6,
url: '#Url.Action("PopulateDataListWithHeader", "DataList")' + "?id=" + YOURID,
dataType: "json",
success: function(result) {
},
error: function(x, e) {
}
});
});

Try This,
function (){
var url = '#Url.Action("SearchReoccurence", "SearchReoccurence", new { errormessage = "__msg__" })';
}

Related

Send string from View to Controller ASP.Net mvc

So we are pretty new to ASP.Net MVC
We have this method that runs when we click on a button in our view. We would like to send the date string to our controller. How can we achieve this?
$('#calendar').fullCalendar({
//weekends : false
dayClick: function(date) {
console.log(date.format());
}
})
This is our controller
[HttpPost]
public IActionResult Booking(string test)
{
var booking = new Booking();
//booking.Date = dateTime;
Console.WriteLine(test);
var viewModel = new BookingsideViewModel
{
Subjects = new[] {"Matematik", "Dansk", "Engelsk"},
Booking = booking
};
return View();
}
you can do it using ajax call,
$.ajax({
url: '#Url.Action("Booking")',
data: { 'test' : date },
type: "post",
cache: false,
success: function (response) {
console.log("success");
},
error: function (error) {
console.log(error.message);
}
});
you can also write url like this:
url:"/ControllerName/ActionName"

After an Ajax GET request to controller method that should return a redirect URL in JSON, I am getting a 500 error and not hitting the AJAX success

The following is the AJAX caller:
function editItem(id) {
$.ajax({
type: 'GET',
url: '/bookmarkrest/edititem?Id=' + id,
success: function (json) {
//alert('Success.');
window.location.href = json.redirectUrl;
},
error: function () {
alert("No Change.");
}
});
};
The following is the method called. The EditLink method should take me to a different page (the specified page):
public ActionResult EditItem(int? Id = 0)
{
try
{
Bookmark bookmark = repository.GetBookmark(Id);
if (bookmark is Link)
{
return Json(new { redirectUrl = Url.Action("EditLink", "BookmarkREST", new { Id = Id }) });
}
return RedirectToAction("Index", "Home");
}
catch (Exception)
{
return RedirectToAction("Index", "Home");
}
}
[HttpGet]
public ActionResult EditLink(int? id)
{
if (id == null)
{
return new HttpStatusCodeResult(HttpStatusCode.BadRequest);
}
Link link = repository.GetLink(id);
if (link == null)
{
return HttpNotFound();
}
return View(new LinkViewModel { name = link.Name, uri = link.URI });
}
I am also getting the correct response in the Chrome Developer tool's Network request response tab:
If I type in the URL, I do access the correct page with data:
I'm not sure why I am kept on the same page, can somebody help?
The Ajax request had to be a POST and datatype attribute included:
function editItem(id) {
$.ajax({
type: 'POST',
datatype: 'JSON',
url: '/bookmarkrest/edititem?Id=' + id,
success: function (json) {
//alert('Success.');
window.location.href = json.redirectUrl;
},
error: function (json) {
alert(json.message);
}
});
};

After getting the search value by Ajax, redirect to result another View

The parameter, search, comes from Index view by Ajax post. After the search process I want to send the employees object to Result view. Result action and view are in the same controller and same view folder. But RedirectToAction(employees) doesn't affect. There is no problem about getting search value from view by Ajax or about getting corresponding employees from database, all of them are fine. This post says you cannot redirect from Ajax post. I don't know how can I redirect & send the employees object to Result view. I don't want to make this via ViewBag.
[HttpPost]
public async Task<IActionResult> Result([FromBody]string search)
{
if (string.IsNullOrEmpty(search))
{
return NotFound();
}
IEnumerable<Employee> employees = await _context.Employees.Where(e => e.Surname == search).ToListAsync();
return RedirectToAction("Index", employees);
}
$(document).ready(function () {
$('.SearchButton').on('click', function (e) {
e.preventDefault();
var searchVal = $('.Search').val();
console.log(searchVal);
$.ajax(
{
type: 'POST',
contentType: 'application/json; charset=utf-8',
url: '#Url.Action("Index", "Employee")',
data: JSON.stringify(searchVal),
dataType: 'json',
success: function (response) {
console.log(response);
},
error: function (response) {
console.log(response.message);
}
});
});
});
I created a Result view instead of trying to redirect to Index view, removed the HttpPost and FromBody attribute from Result action, changed the "return RedirectToAction("Index", employees)" to "return View(employee)"
public async Task<IActionResult> Result(string search)
{
if (string.IsNullOrEmpty(search))
{
return NotFound();
}
IEnumerable<Employee> employees = await _context.Employees.Where(e => e.Surname == search).ToListAsync();
return View(employees);
}
<input type="text" class="Search" placeholder="Search by surname" /><a class="SearchButton">Search</a>
Then delete the whole jQuery code and replace with this lines of code:
$(document).ready(function () {
$('.SearchButton').on('click', function (e) {
window.location.href = '#Url.Action("Result")' + '/?search=' + $('.Search').val();
});
});

Sending parameters of selected values to controller

I have html like this:
HTML
<div class="col-md-3 col-sm-12">
<div>
<p>Región</p>
<select id="lstRegion" class="form-control agenda_space" aria-hidden="true"></select>
</div>
<div>
<p>Solicitud</p>
<select id="lstSolicitud" class="form-control agenda_space" aria-hidden="true"> </select>
</div>
<br/>
<div>
Actualizar Filtro
<br/>
</div>
JS:
$("#lstRegion")
.getJSONCatalog({
onSuccess: function (response) {
console.log(response);
},
url: '/Agenda/GetRegion',
valueProperty: "ID",
textProperty: "valor"
});
//Load solicitud dropdown
$("#lstSolicitud")
.getJSONCatalog({
url: '/Agenda/GetSolicitud',
valueProperty: "ID",
textProperty: "solicitud"
});
Controller:
public ActionResult GetRegion()
{
try
{
var listaRegistros = db.CatalogoRegistros.Where(x => x.CatalogosCodigo == "REGI").Select(x => new
{
x.ID
,
valor = x.Valor
});
return Json(listaRegistros, JsonRequestBehavior.AllowGet);
}
catch (Exception ex)
{
throw ex;
}
}
public ActionResult GetSolicitud()
{
try
{
var listasolicitud = db.Solicitudes.Select(x => new { x.ID, solicitud = "Folio: " + x.ID });
return Json(listasolicitud, JsonRequestBehavior.AllowGet);
}
catch (Exception ex)
{
throw ex;
}
}
They work great I get my dropdwon lists very well, but now I want to do a GET action with selected values of each dropdown when my Actualizar Filtro it´s clicked.
But I´m really new in asp.net and I don´t know what I need to do to get selected values and send to controller.
As googling it I found I need to do method into my controller to get values so:
Controller will be:
public ActionResult GetTareas(string lstRegionValue, string lstsolicitudValue)
{
}
But I don´t know how to send them via JS, how can I do that to receive selected parameters into my controller? Regards
UPDATE
I try it using Ajax like:
$.ajax({
type: 'GET',
url: '#Url.Action("Agenda", "GetTareas")',
data: { region: $('#lstRegion option:selected').html(), solicitud: $('#lstSolicitud option:selected').html() }, // pass the value to the id parameter
dataType: 'json',
success: function (data) {
console.log(data);
}});
But how can I trigger that function when event_add is clicked?
To run your updated ajax code on click, add #event_add click event handler and run your code inside it.
$('#event_add').click(function(e){
e.preventDefault(); //suppress default behavior
$.ajax({
type: 'GET',
url: '#Url.Action("Agenda", "GetTareas")', // don't hard code your urls
data: { region: $('#lstRegion option:selected').html(), solicitud:
$('#lstSolicitud option:selected').html() }, // pass the value to the id parameter
dataType: 'json', // your returning a view, not json
success: function (data) {
console.log(data);
}});
});
Hi Try the below updated code:
$('#event_add').click(function(e){
var regionval = $('#lstRegion option:selected').html(),
var solicval = $('#lstSolicitud option:selected').html(),
$.ajax({
type: 'GET',
url: '#Url.Action("Agenda", "GetTareas", new { lstRegionValue = regionval, lstsolicitudValue =solicval})',
});
});
Note : I didnt test the code, but hope that it should work for you
Controller code:
public ActionResult GetTareas(string lstRegionValue, string lstsolicitudValue)
{
}
Hope it helps , thanks

Extract Div from returned view

I an working on returning view from controller to jquery ,View is returned but i want to extract div from returned view.My Current code is like this
public ActionResult DeleteItem(int pid)
{
//my logic goes here
retutn View("SomeView",model);
}
Jquery
enter code here
script type="text/javascript">
$(document).ready(function () {
$('.Remove').click(function () {
var value = $(this).attr('id');
$.ajax({
cache:true,
type: "POST",
url: "#(Url.Action("DeleteItem", "ControllerName"))",
data: "pid=" + value,
success: function (data) {
$("body").html(data);
},
error:function (xhr, ajaxOptions, thrownError){
alert('Failed to subscribe.');
},
complete: function() { }
});
return false;
});
});
</script>
My current logic returns view and assign total view i.e html+body to body part of page ,which shows html part two times.Is there any way to retrieve div from the returned view and reload it.
thanx in advance
Your controller action should return a PartialViewResult otherwise it will return your layout page in the response. If you want to cater for both scenarios you can check whether the request is an AJAX request:
public ActionResult DeleteItem(int id) {
// delete your item
if (Request.IsAjaxRequest()) {
// return just the partial view
return PartialView("yourview");
}
// otherwise handle normally
return RedirectToAction("list");
}
To understand the difference between returning View and returning PartialView please see What's the difference between "return View()" and "return PartialView()".
script type="text/javascript">
$(document).ready(function () {
$('.Remove').click(function () {
var value = $(this).attr('id');
$.ajax({
cache:true,
type: "POST",
url: "#(Url.Action("DeleteItem", "ControllerName"))",
data: "pid=" + value,
success: function (data) {
var t=$(data).find('.divtoreplacewith');
$('.divtoreplace').replaceWith(d);
//Wasted my 2 days for above two lines.But satisfied with solution,
//Both div are same but '.divtoreplacewith' is having new data,And I have replaced div with that div that's all
},
error:function (xhr, ajaxOptions, thrownError){
alert('Failed to subscribe.');
},
complete: function() { }
});
return false;
});
});

Resources