ASP.NET MVC Javascript ActionResult - asp.net-mvc

Anyone have any examples of javascript actionresults? I am having a hard time getting the script to execute once it has been returned. Thanks

Here's an example I found on a blog post, which actually describes it as an anti-pattern, because the Controller has to have in-depth knowledge of the View in order to function.
public ActionResult DoSomething() {
string s = "$('#some-div').html('Updated!');";
return JavaScript(s);
}

The only way I have found to return a JavascriptResult and execute it on the client is with JQuery:
<script>
$(document).ready(function () {
$("button").click(function () {
$.getScript("/Home/ShowAlert");
});
});
</script>
<button>Use Ajax to get and then run a JavaScript</button>
In the controller:
public JavaScriptResult ShowAlert() {
var script = "alert('Hello');";
return new JavaScriptResult() { Script = script };
}

This might work..
public ActionResult Search(string name)
{
// var someScript = Server.HtmlEncode("<script>alert('Hello')</script>");
return Content("<script>alert('Hello')</script>" );
}

Related

Getting 404 not found when calling Asp.Net Core MVC action from Jquery

I am trying to call index (with Post decorated) in Home controller and post below data (in json format), but its giving me 404 not found.
HomeController.cs
[HttpGet]
public IActionResult Index()
{
return View();
}
[HttpPost]
public async Task<IActionResult> Index(LoginModel model)
{
//login check code
}
client.js
loginUser: function (url, object) {
var data = JSON.stringify(object);
$.post(url, data, function (res) {
if (!res.Message) {
window.location.href = "/Dashboard/Dashboard";
}
});
}
$('#login_id').click(function(){
var loginModel=new Object();
loginModel.Username= "username";
loginModel.Password = "password";
loginUser("Home/Index", loginModel)
});
In above JS code, there is no hit to Index action when $.Post gets execute. Tried with Postman as well as ARC client both.
Thanks
just change this line
loginUser("Home/Index", loginModel)
to this
loginUser("/Home/Index", loginModel)
$('#login_id').click(function(){
var loginModel=new Object();
loginModel.Username= "username";
loginModel.Password = "password";
loginUser("Home/Index", loginModel)
});

View not refreshing after AJAX post

I have a view (Index.cshtml) with a grid (Infragistics JQuery grid) with an imagelink. If a user clicks on this link the following jquery function will be called:
function ConfirmSettingEnddateRemarkToYesterday(remarkID) {
//Some code...
//Call to action.
$.post("Home/SetEnddateRemarkToYesterday", { remarkID: remarkID }, function (result) {
//alert('Succes: ' + remarkID);
//window.location.reload();
//$('#remarksgrid').html(result);
});
}
Commented out you can see an alert for myself and 2 attempts to refresh the view. The location.reload() works, but is basically too much work for the browser. The .html(result) posts the entire index.cshtml + Layout.cshtml double in the remarksgrid div. So that is not correct.
This is the action it calls (SetEnddateRemarkToYesterday):
public ActionResult SetEnddateRemarkToYesterday(int remarkID) {
//Some logic to persist the change to DB.
return RedirectToAction("Index");
}
This is the action it redirects to:
[HttpGet]
public ActionResult Index() {
//Some code to retrieve updated remarks.
//Remarks is pseudo for List<Of Remark>
return View(Remarks);
}
If I don't do window.location.reload after the succesfull AJAX post the view will never reload. I'm new to MVC, but i'm sure there's a better way to do this. I'm not understanding something fundamental here. Perhaps a nudge in the right direction? Thank you in advance.
As you requesting AJAX call, you should redirect using its response
Modify your controller to return JSONResult with landing url:
public ActionResult SetEnddateRemarkToYesterday(int remarkID) {
//Some logic to persist the change to DB.
var redirectUrl = new UrlHelper(Request.RequestContext).Action("Index", "Controller");
return Json(new { Url = redirectUrl });
}
JS Call:
$.post("Home/SetEnddateRemarkToYesterday", { remarkID: remarkID }, function (result) {
window.location.href = result.Url
});
After Ajax post you need to call to specific Url..
like this..
window.location.href = Url
When using jQuery.post the new page is returned via the .done method
jQuery
jQuery.post("Controller/Action", { d1: "test", d2: "test" })
.done(function (data) {
jQuery('#reload').html(data);
});
HTML
<body id="reload">
For me this works. First, I created id="reload" in my form and then using the solution provided by Colin and using Ajax sent data to controller and refreshed my form.
That looks my controller:
[Authorize(Roles = "User")]
[HttpGet]
public IActionResult Action()
{
var model = _service.Get()...;
return View(model);
}
[Authorize(Roles = "User")]
[HttpPost]
public IActionResult Action(object someData)
{
var model = _service.Get()...;
return View(model);
}
View:
<form id="reload" asp-action="Action" asp-controller="Controller" method="post">
.
.
.
</form>
Javascript function and inside this function I added this block:
$.ajax({
url: "/Controller/Action",
type: 'POST',
data: {
__RequestVerificationToken: token, // if you are using identity User
someData: someData
},
success: function (data) {
console.log("Success")
console.log(data);
var parser = new DOMParser();
var htmlDoc = parser.parseFromString(data, 'text/html'); // parse result (type string format HTML)
console.log(htmlDoc);
var form = htmlDoc.getElementById('reload'); // get my form to refresh
console.log(form);
jQuery('#reload').html(form); // refresh form
},
error: function (error) {
console.log("error is " + error);
}
});

$.post() not working if the mvc model view controller has a parameter

I´m new with MVC. I´m using MVC4.
I'm having an issue with a callback. If I alert before and after the post() call both alerts show but the call doesn't fire.
[HttpGet]
[Authorize]
public ActionResult Dashboard(int Menu)
{
//some code
return View("Dashboard");
}
<script>
$(document).ready(function () {
$.post("../Client/GetFact", {},
function (data) {
//some code
});
});
</script>
[HttpPost]
[Authorize]
public JsonResult GetFact()
{
//some code to fill object_data
var data = object_data;
return Json(data);
}
As long as I leave ActionResult Dashboard without a parameter is works. If I add a parameter to Dashboard(int Menu) then the call back to GetFact doesn't work.
I searched and found a similar post and follow the instructions given by you guys, but still does not work( looked at: getJSON not working if the mvc model view controller has a parameter).
I do not know what I'm doing wrong. Can you help? Thank's!
I do something similar with $.get, using jquery with the #Url.Action instead of the url.
in addition to using the FormContext to pass to my Action :
Place just before #using (Html.BeginForm())
#{ ViewContext.FormContext = new FormContext(); }
example :
$.get('#Url.Action("ActionName", "ControllerName")', { IDName: $('#IdName').val() }, function (data) {
//Do Something here with the data
});
I would imagine form post would be
$.post('#Url.Ation("ActionName", "ControllerName")', function (data) {
//Do Something here with the data
});
This is a shorthand Ajax function, which is equivalent to:
$.ajax({ type: "POST",
url: url,
data: data,
success: success,// -> call alert here
dataType: dataType});

MVC application, set session variables then open asp.net popup

I'm wondering if it is possible to achieve the following.
Within an MVC application -
Have a link which queries a database for some values, sets those values as session variables and then opens a pop-up window(which is an asp.net webform within the MVC app)
It's basically to allow us to run Crystal Reports, the link would set the Report ID in a session variable which would then be accessible in the asp.net webform.
My confusion is the setting of the session variable on click of the link and then opening the popup.
Can it be done and if so any links or pointers?
Edit:
Javascript
<script language="javascript" type="text/javascript">
function flagInappropriate(postId) {
var url = "/Home/FlagAsInappropriate/" + postId;
$.post(url, function(data) {
if (data) {
alert("True")
} else {
// callback to show error/permission
}
});
}
Controller
namespace MvcApplication1.Controllers
{
[HandleError]
public class HomeController : Controller
{
[AcceptVerbs("POST")]
public bool FlagAsInappropriate(int id)
{
// check permission
bool allow = true;
// if allow then flag post
if (allow)
{
// flag post
return true;
}
else
{
return false;
}
}
public ActionResult Index()
{
ViewData["Message"] = "Welcome to ASP.NET MVC!";
return View();
}
public ActionResult About()
{
return View();
}
}
}
It can be done, yes. I've achieved something similar for the purposes of generating reports (predominantly so the report URL is hidden from the user and so some tracking and authentication could be achieved using once-off tokens). My solution was as follows:
Perform an AJAX call to a Web Method in your application to set the relevant session variable(s).
Return a value from the Web Method to indicate whether it was successful.
For the "success" event handler of the AJAX call, open your relevant ASPX page to generate the report.
Simple as that. :)
Here's some sample code to attach the click event and do the AJAX call, based on your amended question:
Click to test AJAX call
<script type="text/javascript">
$(document).ready(function () {
$(".flag").click(function () {
flagInappropriate($(this).attr("id").split("-")[1]);
});
});
function flagInappropriate(postId) {
var url = "/Home/FlagAsInappropriate/" + postId;
alert(url);
$.post(url, function (data) {
if (data) {
alert(data);
} else {
// callback to show error/permission
}
});
}
</script>

ASP.NET MVC with jQuery

I'm currently attempting to retrieve a list of objects from my database using jQuery. I have been attempting to use getJSON but the callback is never fired. However, if I use
$.post(url, data, callback)
... then it seems to fire just fine.
My controller actions is thus:
public ActionResult GetTemplates()
{
IEnumerable<Template> templates = TemplateDAO.GetTemplates();
List<TemplateViewModel> jsonTemplates = new List<TemplateViewModel>();
foreach(Template t in templates)
{
TemplateViewModel tvm = new TemplateViewModel(t.ID, t.TemplateName);
jsonTemplates.Add(tvm);
}
return Json(jsonTemplates.ToList());
}
and the TemplateViewModel is:
public class TemplateViewModel
{
public int ID {get; set; }
public string TemplateName {get; set; }
}
The javascript I'm attempting to use is:
function LoadTemplates() {
alert("loading templates");
var url = '<%= Url.Action("GetTemplates", "Project") %>';
$.getJSON(url, null, function(data) {
alert("Succeeded" + data);
});
}
This javascript does not show the "Succeeded" alert for some reason, whereas replacing the getJSON call with
$.post(url, null, updateTemplates, 'json');
works.
Any ideas?
It's more of a curiosity thing now that $.post works, but I'd like to know what I'm doing wrong, as every example I've seen looks exactly like mine!
Cheers,
Chris
Try this:
return Json(jsonTemplates.ToList(), JsonRequestBehavior.AllowGet);

Resources