I've created an UmbracoApiController named FormDatasourceController that resides in my plugin area to be used in ajax calls to get or post data.
[PluginController("AreaName")]
public class FormDatasourceController : UmbracoApiController
{
[HttpGet]
public IEnumerable<ICountry> GetAllCountries()
{
return MerchelloConfiguration.Current.MerchelloCountries().Countries;
}
}
and in the cshtml file I have this request
<script type="text/javascript">
$(function(){
$('#sbmtBtn').on("click", function () {
$.get('~/Umbraco/AreaName/FormDatasource/GetAllCountries', null)
.success(function (data) {
alert(data);
})
.fail(function (e) {
alert('failed' + e);
});
});
});
However, I always get error status 404. I tried to EnableCors but with no luck.
Any advise? I'm using umbraco 7
Edit:
For AngularJs controllers/resources in Umbraco, just do this:
change
$.get('~/Umbraco/AreaName/FormDatasource/GetAllCountries', null)
to
$.get('AreaName/FormDatasource/GetAllCountries', null)
That should get your call working. Ignore the ~/Umbraco/ bit.
Your API call should look:
~/Umbraco/AreaName/FormDatasource/GetAllCountries
See "Plugin based controller" at https://our.umbraco.org/documentation/Reference/Routing/WebApi/#plugin-based-controller.
Note, if you had inherited from 'UmbracoAuthorizedApiController' or 'UmbracoAuthorizedJsonController' your api call should be something like this:
~/Umbraco/backoffice/AreaName/FormDatasource/GetAllCountries
For more information, take a look at the bottom of this page in the documentation site under Backoffice Controllers:
https://our.umbraco.org/documentation/Reference/Routing/WebApi/
Related
I'm working on an ASP.NET MVC app. A Razor view in the app is loaded by visiting a route that looks like this:
http://localhost:somePort/objects/edit/{id}
The id is optional. When a user visits this view, I initialize a third-party JQuery plugin. I need to get the ID value from the URL and put it into the initialization. If its null, leave it off. If it exists, add it. Currently, I'm trying the following:
$(function () {
var myPlugin = new Plugin("div#myId", {
url: "/api/PostData/#Request.Params["id"]",
init: function () {
// do stuff
}
});
});
Unfortunately, the url always shows /api/PostData/. Its like it doesn't see the ID value in the URL. How do I put that value here?
You could just put the id into your model from your controller. Then you could do this:
$(function () {
var myPlugin = new Plugin("div#myId", {
url: "/api/PostData/#Model.Id,
init: function () {
// do stuff
}
});
});
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});
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>
I have two user controls on the page and one of the user control has this text aread.
which is used to add a note and but when they click add note button the page reloads.
I do not want the page to reload ,i was looking for an example which this is done without
postback.
Thanks
i tired doing this using JSON , but it throws the following error
The HTTP verb POST used to access path '/Documents/TestNote/Documents/AddNote' is not allowed.
<script type="text/javascript">
$(document).ready(function() {
$("#btnAddNote").click(function() {
alert("knock knock");
var gnote = getNotes();
//var notes = $("#txtNote").val();
if (gnote == null) {
alert("Note is null");
return;
}
$.post("Documents/AddNote", gnote, function(data) {
var msg = data.Msg;
$("#resultMsg").html(msg);
});
});
});
function getNotes() {
alert("I am in getNotes function");
var notes = $("#txtNote").val();
if (notes == "")
alert("notes is empty");
return (notes == "") ? null : { Note: notes };
}
</script>
</asp:Content>
Something like this would give you the ability to send data to an action do some logic and return a Json result then you can update your View accordingly.
Javascript Function
function AddNote(){
var d = new Date(); // IE hack to prevent caching
$.getJSON('/MyController/MyAction', { data: "hello world", Date: d.getTime() }, function(data) {
alert(data);
// call back update your view here
});
}
MyController Action
public virtual JsonResult MyAction(string data)
{
// do stuff with your data here, which right now my data equals hello world for this example
return Json("ReturnSomeObject");
}
What you want is AJAX update. There will always be a postback (unless you are satisfied with simple Javascript page update that does not save on the server), but it won't be the flashing screen effect any more.
If I have a Controller called "HomeController" and I'm on the Index page of that controller, how can I do a jQuery Ajax post to another controller.
I tried the below,
$.post("/DetailedQuote/jQueryGetDetailedQuote", { productCode: "LPJ" }, function(newHTML) {
alert(88);
});
I have a DetailedQuoteController.
I have also tried;
post("DetailedQuote/
post("DetailedQuote.aspx/
post("/DetailedQuote.aspx/
post("/DetailedQuoteController/
post("DetailedQuoteController/
post("DetailedQuoteController.aspx/
post("/DetailedQuoteController.aspx/
And still no joy.
I should also mention that this is running a Hybrid WebForms and MVC site on IIS 6.
EDIT
The error that is being returned in error: is "error" so I assume that's maybe a 404.
In fact, it is a 404. I just checked.
This should work:
public class DetailedQuoteController : Controller
{
[HttpPost]
public ActionResult GetDetailedQuote(string productCode)
{
return Json(new { Code = productCode, Quote = 123 });
}
}
And to invoke it first declare a global javascript variable containing the address of this controller somewhere inside the view:
var quoteAddress = '<%= Url.RouteUrl(new { controller = "DetailedQuote", action = "GetDetailedQuote" }) %>';
And finally call the method:
$(function() {
$.post(quoteAddress, { productCode: 'LPJ' }, function(json) {
alert(json.Quote);
});
});
There doesn't appear to be anything wrong with your jQuery command, so the most obvious place to start looking is in the controller itself. Things to check would be:
Does your Controller action return a Json response (e.g. public JsonResult jQueryGetDetailedQuote)?
Are you using the Json() method to return your object?
Do you have your action decorated with the [HttpPost] attribute?
Perhaps you could post part of your controller code as well?
I notice that in your jQuery method you're calling an action called jQueryGetDetailedQuote. If your intention is purely to just GET a result, then perhaps you should use jQuery's $.get() or $.getJSON() functions instead?