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'm new to asp.net, Im posting all my data to server using $.post (Jquery syntax).
Action of controller is executed # the end I'm calling RedirectToAction to different action method, after completion of action method execution.
Eecution reaches to completed callback event of $.Post() where im loading result of request in html to root element of page. $(html).html(results).
How can i use $.post with RedirectToAction
What's the point of using AJAX when you replace the whole page? The whole point of AJAX is to refresh only a certain portion of the DOM. If you are going to refresh your entire page, then simply use a standard link, no need of AJAX. But if we suppose that your controller action handles 2 cases: one in which it returns a partial view and one in which it redirects, you could pass the target url as JSON:
[HttpPost]
public ActionResult SomeAction()
{
if (Something)
{
return PartialView();
}
return Json(new { redirectTo = Url.Action("Foo", "Bar") });
}
and then on the client:
$.post('#Url.Action("SomeAction")', function(result) {
if (result.redirectTo) {
// the controller action passed us the url to redirect to
window.location.href = result.redirectTo;
} else {
// the controller action passed us a partial result =>
// let's update some portion of the DOM
$('#someId').html(result);
}
});
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
ASP.NET MVC 2.0 will now, by default, throw an exception when an action attempts to return JSON in response to a GET request. I know this can be overridden on a method by method basis by using JsonRequestBehavior.AllowGet, but is it possible to set on a controller or higher basis (possibly the web.config)?
Update: Per Levi's comment, this is what I ended up using-
protected override JsonResult Json(object data, string contentType, System.Text.Encoding contentEncoding)
{
return Json(data, contentType, JsonRequestBehavior.AllowGet);
}
This, like other MVC-specific settings, is not settable via Web.config. But you have two options:
Override the Controller.Json(object, string, Encoding) overload to call Json(object, string, Encoding, JsonRequestBehavior), passing JsonRequestBehavior.AllowGet as the last argument. If you want this to apply to all controllers, then do this inside an abstract base controller class, then have all your controllers subclass that abstract class.
Make an extension method MyJson(this Controller, ...) which creates a JsonResult and sets the appropriate properties, then call it from your controller via this.MyJson(...).
There's another option. Use Action Filters.
Create a new ActionFilterAttribute, apply it to your controller or a specific action (depending on your needs). This should suffice:
public class JsonRequestBehaviorAttribute : ActionFilterAttribute
{
private JsonRequestBehavior Behavior { get; set; }
public JsonRequestBehaviorAttribute()
{
Behavior = JsonRequestBehavior.AllowGet;
}
public override void OnResultExecuting(ResultExecutingContext filterContext)
{
var result = filterContext.Result as JsonResult;
if (result != null)
{
result.JsonRequestBehavior = Behavior;
}
}
}
Then apply it like this:
[JsonRequestBehavior]
public class Upload2Controller : Controller
MVC 2 block Json for GET requests for security reasons. If you want to override that behavior, check out the overload for Json that accepts a JsonRequestBehavior parameter.
public ActionResult Index()
{
return Json(data, JsonRequestBehavior.AllowGet)
}
I also got this error when I first use MVC 2.0 using my old code in MVC 1.0. I use fiddler to identify the cause of the error. See the steps on how to troubleshoot it using Fidder -
http://www.rodcerrada.com/post/2011/07/11/jQuery-getJSON()-does-not-tirgger-the-callback-in-ASPNET-MVC-2.aspx
Is this is the security issue MVC2 was trying to address?
http://haacked.com/archive/2009/06/25/json-hijacking.aspx
If so, it seems like the vulnerability is only an issue if you are trying to do a json call to an outside website. If your MVC2 app is only making json calls to your own website (to fill jqgrids for example), shouldn't you be able to safely override the Json call in your base controller to always allow get?
Just change JSON code from :
$.getJson("methodname/" + ID, null, function (data, textStatus)
to:
$.post("methodname/" + ID, null, function (data, textStatus)
What is the best practice to support data for asp.net 2.0-3.5 ajax web application?
I don't want to use update panels, just plain text data (JSON).
Should I use web services? Or is there another way.
Errrr... Use an .aspx page ? What are handlers for ?
You just have to create a generic base handler that will take care of json (de)serialization (e.g. using Json.net) and then implement handlers for your ajax calls.
public abstract class JsonHandlerBase<TInput, TOutput> : IHttpHandler
{
public void ProcessRequest(HttpContext context)
{
context.Response.ContentType = "application/json";
TInput input = (TInput)context.Request; // Desesialize input
TOutput output = ProcessRequest(context, parameter);
string json = (string)output; // Serialize output
context.Response.Write(json);
}
public abstract TOutput ProcessRequest(HttpContext context, TInput input);
public bool IsReusable { get { return false; } }
}
This is just an example, it's up to you to decide want you need in your base handler.
You can use plain aspx pages or handlers and just output JSON. You do this by erasing all the Html in the aspx and then using Response.Write() in the code.
Then for the front end JS you can use JQuery or any other Ajax framework.
You may also want to check out Asp.Net MVC. MVC has a JsonResult resonse type and is very easy to use together with JQuery to get very good Ajax functionality.