Calling controller action from javascript in view - javascript

I want to call action from view using JavaScript, but I can't do this:
Here is my code:
#if (ViewBag.Status == true)
{
<script language="javascript" type="text/javascript">
if (confirm("Some message"));
//And here i want to add action call
</script>
}
I'm trying to use #Html.Action, but this ruined script code and confirm message didn't show.
When I write it as shown here: Calling ASP.NET MVC Action Methods from JavaScript:
#if (ViewBag.Status == true)
{
<script language="javascript" type="text/javascript">
if (confirm("Some message"));
{
$.ajax({
url: 'MyController/MyAction',
data: { id: id },
success: function () {
alert('Added');
}
});
}
</script>
}
nothing changed. It displays confirmation dialog but don't calling method

You need to change your code to something like this.In which case you would call: func(#ViewBag.Status)
#Section scripts
<script language="javascript" type="text/javascript">
//val in this case being the value of the ViewBag passed from where the call is occurring
function func(val) {
if (val == true) {
if (confirm("Some message"));
{
$.ajax({
url: 'MyController/MyAction',
data: { id: id },
type: "POST",
success: function () {
alert('Added');
}
});
}
}
}
</script>
end section
Also in the controller remember to apply the [HttpPost] attribute on the method like so:
[HttpPost]
public ActionResult MyAction(string id)
{
// your code
return Json();//your response
}

If i understood you correctly, you want to call your Action method in controller from javascript. And show confirm message on success.
Here is the code for that:
if ('#ViewBag.Status' == true)
{
$.ajax({
type: "Post",
url: '#Url.Action("MyAction", "MyController")',
data: { Id: Id },
dataType: "json",
traditional: true,
success: function (data) {
alert("Success");
},
});
}
To hit the success, you need to return the JsonResult or ContentResult or ActionResult from controller.

JavaScript cannot call a controller action unless you use Ajax or another client side mechanism to talk to the server!
What you need it to use xhr to tak to the server or use following jQuery code
<script src='jquery-latest.js'></script>
#if (ViewBag.Status == true)
{
<script language="javascript" type="text/javascript">
if (confirm("Some message")){
//And here i want to add action call
$.get('#Url("action","controller",null)')
.done(function(data){
//use loaded data here
}).fail(function(e,f,g){
console.log({e:e,f:f,g:g})
});
}
</script>
}
PS: don't forget to reference the jQuery library

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.

This JS code works properly in the .cshtml file, but not working in .js file(external javascript file)

This JS code works properly in the .cshtml file, but not working in .js file(external javascript file). Can anyone help me? i am also trying with Ajax GET but also not working in js file
[Area("Administrator")]
[Authorize(Roles = "Administrator")]
public class HomeController : Controller
{
private readonly ApplicationDbContext _context;
public HomeController(ApplicationDbContext context)
{
_context = context;
}
public JsonResult EarningChart()
{
var earning = _context.Orders.Where(o => o.Status == OrderStatus.Completed).ToList();
return Json (earning);
}
<script type="text/javascript">
$(function () {
//ajax function for fetch data
$.ajax({
type: "GET",
url: '#Url.Action("EarningChart","Home",new { area ="Administrator"})',
success: function (data) {
alert('succeed');
},
error: function () {
alert('Failed');
}
});
});
</script>
#Url.Action() is razor (server side) code and can't be used in .js file .You can add a hidden field in your main page to store url, then use javascript/jquery to get the url from the hidden field in .js file :
#Html.Hidden("MyURL", Url.Action("EarningChart","Home",,new { area ="Administrator"}))
Then in your js file :
<script type="text/javascript">
$(function () {
var myUrl = $("#MyURL").val();
//ajax function for fetch data
$.ajax({
type: "GET",
url: myUrl,
success: function (data) {
alert('succeed');
},
error: function () {
alert('Failed');
}
});
});
</script>
You don't show any js file or any cshtml file
From your comments I see you have :
<script type="text/javascript"> $(function () { //ajax function for fetch data $.ajax({ type: "GET", url: '#Url.Action("EarningChart","Home",new { area ="Administrator"})', success: function (data) { alert('succeed'); }, error: function () { alert('failed'); } }); }); </script>
I will assume your question is that if you have above code in your cshtml file it works but if you have above code in a seperate js file it doesn't work
In order to include your js file you need to include it in your cshtml page like this:
<script src="yourJsFilePathHere"></script>

MVC5 Ajax update

I have a dropdown with selection id StaffId. What I am doing is once an item is selected I want to pass on the StaffId to controller to fetch records in a database using the staffId. This is giving an error on page load without passing the StaffId to the controller. below is the snippet
controller
[HttpPost]
public PartialViewResult GetStaffPosts(int? id)
{
var sPost = db.StaffPosts.Where(a => a.StaffId == id.Value);
return PartialView(sPost.ToList());
}
<div id="divPartialView">
#{Html.RenderPartial("GetStaffPosts");}
</div>
<script type="text/javascript">
$(document).ready(function () {
$("#StaffId").change(function (event) {
var options = {};
options.url= "/StaffPost/GetStaffPosts/" + $(this).val(),
options.data= { id: $(this).val() },
options.cache= false,
optionstype= "POST",
options.dataType= "html",
options.success= function (data, textStatus, XMLHttpRequest) {
$("#divPartialView").html(data); // HTML DOM replace
$.ajax(options);
}
});
});
</script>
Your current code is not actually making an ajax call on the change event because you are invoking the $.ajax(options); call inside the success callback of the options object. You are not calling the $.ajax method on the change event!
This should work (assuming your controller code is returning a 200 response).
$("#StaffId").change(function (event) {
var options = {};
options.url= "/StaffPost/GetStaffPosts/" + $(this).val(),
options.data= { id: $(this).val() },
options.cache= false,
options.type= "POST",
options.dataType= "html",
options.success= function (data, textStatus, XMLHttpRequest) {
$("#divPartialView").html(data); // HTML DOM replace
}
$.ajax(options);
});
You may also simplify your code using the $.post method.
$("#StaffId").change(function() {
$.post("/StaffPost/GetStaffPosts/",{ id: $(this).val() } ,function (data) {
$("#divPartialView").html(data);
});
});
Or even using the $.load method and a one liner
$("#StaffId").change(function(event) {
$("#divPartialView").load("/StaffPost/GetStaffPosts/", { id: $(this).val() });
});
Hi just put your ajax call outside of the success function and make an url like the below code and try again
Your changed code:
<script type="text/javascript">
$(document).ready(function () {
$("#StaffId").change(function (event) {
var options = {};
options.url= "../StaffPost/GetStaffPosts,
options.data= { id: $(this).val() },
options.cache= false,
optionstype= "POST",
options.dataType= "html",
options.success= function (data, textStatus, XMLHttpRequest)
{
$("#divPartialView").html(data); // HTML DOM replace
}
$.ajax(options);
});
});
</script>

create a folder once a button click in asp.net mvc

I'm creating asp.net mvc 5 application.In that application I want generate a Folder once I click a button on front end view page.
I want to generate that folder with in following location ~/Essential_Folder/
<input type = "button" value="Create_Folder" class="btn btn-default" id="create_folder"/>
How can I do this ,
can I do this using Server side language (in my case its C#), if its how ?
is this possible to do using client side language (such as JavaScript) ?
script
<script type="text/javascript">
$('btn-default').click(function () {
});
</script>
As #Stephen mentioned, you need to use ajax in order to create a folder. So you can have an action method like this:
[HttpPost]
public JsonResult CreateDirectory()
{
//if location has folder called "Essential_Folder" it should allow to goto inside of this if condition
if (Directory.Exists(Server.MapPath("~/Content/Essential_Folder/")))
{
Directory.CreateDirectory(Server.MapPath(string.Format("~/Content/Essential_Folder/NewDir_{0}",
DateTime.Now.Millisecond)));
return Json("OK");
}
return Json("NO");
}
And your ajax call should something like this:
<script type="text/javascript">
$('.btn').click(function() {
$.ajax({
url: "#Url.Action("CreateDirectory")",
type: "POST",
contentType: "application/json; charset=utf-8",
dataType: "json",
error: function (response) {
alert(response.responseText);
},
success: function (response) {
if (response === 'OK')
alert("Directory has been created");
else
alert("errro");
}
});
});
</script>

MVC3 AJAX passing data to controller. It's being submitted twice

So I have a table that gets transformed to an array using:
var result = $("#enrolledStudents").sortable('toArray');
But when I go a head an pass that into my controller like so:
$("#update-enroll").click(function () {
var result = $("#enrolledStudents").sortable('toArray');
$.ajax({
url: '#Url.Action("Enrollment", "Classroom")',
data: { students: result },
type: 'POST',
traditional: true
});
});
My debugging breakpoint gets set off twice, causing issues to arise. What is the proper way to submit data to my controller on POST?
Per my comments, there are a couple things that could be causing this.
You have have the unobtrusive file(s) loaded multiple times
Your form has an action method defined, and your button is inside the form tag as a submit button. This will submit the form, and then the click will also submit the form - see example
Example
<form action="/somerowout/someaction">
<input type="text" id="text1"/>
<input type="text" id="text1"/>
<input type="submit" />
</form>
If you need to validate a value on your form before posting, don't hook up an additional Ajax call. Your javascript will look something like:
$(document).ready(function () {
$("form").submit(function(){
var result = $("#enrolledStudents").sortable('toArray');
if(result == null){
//do something to show validation failed
return false;
}
return true;
});
});
And your form code would then look something like:
#using (#Ajax.BeginForm(new AjaxOptions { })) {
<input type="text" id="text1"/>
<input type="text" id="text1"/>
<input type="submit" />
}
If you want to use Ajax rather than the Html Helpers, use a div instead of a form, and you won't get a duplicate post. Here's how you could achieve this:
<div id="enrolledStudents">
<--! your elements -->
<button id="saveStudents">Save</button>
</div>
JavaScript
$(document).ready(function () {
$("saveStudents").click(function(){
var result = $("#enrolledStudents").sortable('toArray');
if(result !== null){ /* do some kind of check here. */
$.ajax({
url: '#Url.Action("Enrollment", "Classroom")',
data: { students: result },
type: 'POST',
traditional: true,
success : function(data) {
if (data.status) {
window.location = data.route;
}
}
})
} else {
/* notify ui that save didn't happpen */
}
});
});
Example Controller Action
When posting your data using Ajax, here's an example of how to pass the route
[HttpPost]
public ActionResult SomethingPost(SomeModel model) {
if (Request.IsAjaxRequest()) {
var json = new {
status = true,
route = #Url.RouteUrl("MyRouteName", new { /* route values */ })
};
return Json(json, JsonRequestBehavior.AllowGet);
}
}
Are you sure you are preventing the default behaviour (form POSTING) of the submit button ? use preventDefault to do so.
$("#update-enroll").click(function (e) {
e.preventDefault();
//rest of the code
});
EDIT : As per the comment
To do the redirect in the ajax handler, you need to return the URL to be redirected in a JSON Response back to the calle.
[HttpPost]
public ActionResult Classroom(string students)
{
//do some operaton
if(Request.IsAjax())
{
//This is an Ajax call
return Json(new
{
Status="Success",
NewUrl = Url.Action("Index","Home")
});
}
else
{
//Normal request. Use RedirectToActiom
return RedirectToAction("Index","Home");
}
}
Now in your ajax call check the JSON result and do the redirect.
$.ajax({
url: '#Url.Action("Enrollment", "Classroom")',
data: { students: result },
type: 'POST',
dataType: "json",
contentType: "application/json; charset=utf-8",
success: function (data) {
if(data.Status=="Success")
{
window.location.href = data.Newrl;
}
else
{
alert("some error");
}
}
});
Check if you don't have the jquery files loaded twice. I had this behavior and the problem was files loaded twice.

Categories

Resources