I am in a legacy asp.net application and I need to call a method within a class via jQuery ajax post.
So far I have a class called NewClass with a single method;
[WebMethod]
public string jQuery_GetCategoryDescription(string CategoryName)
{
return "Slappy";
}
I then have the following jQuery;
$.post('/NewClass/jQuery_GetCategoryDescription', { CategoryName: "trippy" }, function (newHTML) {
alert(newHTML);
});
I've tried putting in the whole namespace in.
However I can't seem to call the method within the class.
EDIT
I am getting a 405 error
If the
[WebMethod]
public string jQuery_GetCategoryDescription(string CategoryName)
{
return "Slappy";
}
Is in side Index.aspx
You can call it by /Index.aspx/jQuery_GetCategoryDescription
Related
How to use AJAX for ViewComponent in Asp.Net Core? That is calling the method #Component.Invoke ("ComponentName", SomeData); ViewComponent will involve various views depending on SomeData without rebooting the main view.
Update
My solution is:
$(function () {
$(Container).load('ControllerName/ControllerAction', {
ArgumentName: ArgumentValue });
});
Controller :
public IActionResult ControllerAction(string value)
{
return ViewComponent("ViewComponent", value);
}
Is there a way to directly use a ViewComponent as AjaxHelpers in previous versions?
Your solution is correct. From the docs:
[ViewComponents are] not reachable directly as an HTTP endpoint, they're invoked from your code (usually in a view). A view component never handles a request.
While view components don't define endpoints like controllers, you can easily implement a controller action that returns the content of a ViewComponentResult.
So as you suggested, a lightweight controller can act as an AJAX proxy to our ViewComponent.
public class MyViewComponentController : Controller
{
[HttpGet]
public IActionResult Get(int id)
{
return ViewComponent("MyViewComponent", new { id });
}
}
I am working on a project in VS 2013 using ASP.NET MVC. In one of my cshtml files, I have the following code to return a value (here, and integer):
$.ajax({
url: '/myproject/api/Test',
type: 'GET',
success: function (data) {
UseResults(data);
},
error: function (msg) {
alert(msg);
}
});
The file this routes to, TestController.cs, has this code:
namespace MyProject.Controllers
{
public class TestController : ApiController
{
public int Get()
{
return GetThisValue();
}
public int GetThisValue()
{
//Do work to find and return value...
}
}
}
This code currently works properly. It does so by having the ajax call route to the Get() function, which returns the correct value from the GetThisValue() function. However, it is tedious to need the separate Get() function when all it does is call another function. Also, in this program, there will be many different functions using the "GET" method in Ajax, and while it would be possible to route them all through Get(), it would be a lot less cluttered for us to be able to call GetThisValue() directly in the ajax call instead of through Get(). My question is, is there any way to use ajax to route directly to a function that uses [HttpGet] instead of needing it to route first to Get() and then to the other function from there? (Sorry if I didn't put this into words great, if clarification is needed on anything please ask)
It's easy with attribute routing...
[Route("/myproject/api/test")]
[Route("/some/other/route")]
[Route("/yet/another/route")]
public int GetThisValue()
{
//Do work to find and return value...
}
You can set up all the separate routes you want to point to that same method.
In our WebApplication we have a lot of [WebMethod] calls. For the purpose of security we want to check if its a logged in user or not (using session). How can I check it without writing code inside all WebMethods?
eg.
[WebMethod]
public static bool WebMethodCall()
{// check if its a logged in user or not before executing the webmethod
return true;
}
I am giving you this answer by example
i have webservice named common.cs
now
public class Common : System.Web.Services.WebService
{
public Common ()
{
//here you can check your session so when ever your
webmethod will be executed this code will call first then your webmethod
}
//this webmethod will be executed after common
[WebMethod]
public static bool WebMethodCall()
{// check if its a logged in user or not before executing the webmethod
return true;
}
[WebMethod]
public static bool WebMethodCall1()
{// check if its a logged in user or not before executing the webmethod
return true;
}
}
So explaination will be like this
you have common class named common and two webmethod webmethodcall and webmethodcall1
add your common code in common
I hope this will help you regards...:)
My first thought is to utilize a custom httpModule. However, further readings indicate using SoapExtensions can do the trick. See example:
http://www.hanselman.com/blog/ASMXSoapExtensionToStripOutWhitespaceAndNewLines.aspx
I'm working with MVC 4 Web API and I have this dummy ValueProvider:
DummyValueProvider.cs
class DummyValueProvider : IValueProvider
{
public DummyValueProvider()
{
}
public bool ContainsPrefix(string prefix)
{
return true;
}
public ValueProviderResult GetValue(string key)
{
return new ValueProviderResult("testing", "testing", System.Globalization.CultureInfo.InvariantCulture);
}
}
class DummyValueProviderFactory : System.Web.Http.ValueProviders.ValueProviderFactory
{
public override IValueProvider GetValueProvider(System.Web.Http.Controllers.HttpActionContext actionContext)
{
return new DummyValueProvider();
}
}
This ValueProvider should return true for any key asked, so it will always supply a value to the model binder when it needs. The ValueProvider is registered in the WebApiConfig like this:
WebApiConfig.cs
config.Services.Add(typeof(ValueProviderFactory), new DummyValueProviderFactory());
The code compiles and runs fine.
I also have this action in the Account API controller:
AccountController.cs
public HttpResponseMessage Register(string foo) { ... }
The action gets called fine when I call it like below:
/register?foo=bar
And foo is filled with bar as expected; but if I call:
/register
The server returns 404 with the message No HTTP resource was found that matches the request URI 'http://localhost:14459/register'.
Also, I put breakpoints inside methods ContainsPrefix() and GetValue(), but they never get triggered.
What am I doing wrong? Shouldn't DummyValueProvider be providing the value testing to parameter foo?
Try this
public HttpResponseMessage Get([ValueProvider(typeof(DummyValueProviderFactory))] string foo) {... }
I higly suggest you to read this recent article to customize Web Api Binding.
Update:
After reading the article the OP was able to discover the solution. It was that using the parameter attribute [ModelBinder] was required for it to work. This was because unless the parameter is annotated, [FromUri] is assumed. Once annotated with [ModelBinder] the registered handlers are executed.
I used to use asmx to handle ajax calls from pages, but I have read that it's a legacy product, and it is not very compatible with MVC applications. What's the replacement for asmx that is also compatible with MVC nowadays?
Use Action methods in your controllers to give you the Ajax response. You can return any form of data like HTML markup (using a view, Json, string . Image etc...)
public ActionResult GetItems()
{
var items=dbContext.Items;
return Json(items,JsonRequestBehavior.AllowGet);
}
public ActionResult GetAnother()
{
return Content("I am just string from ajax");
}
You can use same action result for returning HTML markup for an ajax request and normal request using the Request.IsAjax method
public ActionResul Getcustomer(int id)
{
var customer=dbcontext.Customer.Find(id);
if(Request.IsAjax())
{
return View("PartialCustomerForm",customer);
}
return View("RegularCustomerForm",customer);
}
To call these methods from your page, you can use jquery ajax
$.get("#Url.Action("GetItems","Customer")", { id: 3 },function(data){
//do whatever with the response. //alert(data);
});