Remote model annotation refreshes page on success - asp.net-core

Model Class
[Remote(
"isExaminationTemplateInUse",
"GENExaminationTemplate",
AdditionalFields = "ExaminationTemplateID",
ErrorMessage = "Template Name already exists.",
HttpMethod = "POST"
)]
[Required(ErrorMessage = "Template Name is required.")]
[DisplayName("Name")]
public String ExaminationTemplateName { get; set; }
Controller
[HttpGet]
[HttpPost]
[Route("isExaminationTemplateInUse")]
public async Task<ActionResult> isExaminationTemplateInUse(String ExaminationTemplateName, int ExaminationTemplateID)
{
return Json(true);
}
AJAX Part
//Submit Main Form.
$(document.body).on("submit", "#mainForm", function (event) {
//Prevent Default Region.
event.preventDefault();
//Post Region.
//Serialize the form datas.
$.ajax({
url: '/GENExaminationTemplate/SetExaminationTemplate',
type: "post",
async: true,
data: { pstrJSONMasterData: jsonMasterData },
success: function (response) {
window.location.href = response;
}
});
});
Add New Record Mode, Works Fine. Reason: In this mode focus moves through the field and on submit it does not go for validation.
Edit Record Mode, Not Works Fine. Reason: Focus not moves through the field, On click of submit button system moves into action "isExaminationTemplateInUse" and on line "return Json(true);" refreshes page, that moves to page load function rather page save function. However, by just passing focus through the field that is using [Remote], system works fine.
In scripts section following file references are also present on top of the page.
jquery.js,jquery.validate.js, jquery.validate.unobtrusive.js

Related

How to make an admin ajax call in prestashop 1.7.6

I'm trying to make an ajax call in Prestashop Admin:
I created a module without a config page. It just add a button in some backoffice page, I'm trying to make an ajax call to my module file without success.
Making an ajax call in frontend is working (I added an ajax.php file in my modules/mymodule/controller/front/ directory), I tried to do the same thing for admin but it's not working at all.
What I've done:
loading the js file from actionAdminControllerSetMedia is ok
adding this in the composer.json file:
"autoload": {
"psr-4": {
"MyModule\\Controller\\": "controllers/admin/"
},
"config": {
"prepend-autoloader": false
},
created the controllers/admin/ajax.php file with this code (based on this documentation code):
namespace MyModule\Controller;
use PrestaShopBundle\Controller\Admin\FrameworkBundleAdminController;
class DemoController extends FrameworkBundleAdminController
{
public $auth = false;
public $ssl = true;
public $ajax = true;
public $errors = false;
public $message;
public function __construct()
{
parent::__construct();
}
public function initContent()
{
parent::initContent();
}
public function postProcess()
{
PrestaShopLogger::addLog("MODULE CONTROLLER OK ", 1);
}
public function displayAjax()
{
$this->ajaxDie(json_encode(array('success'=> !$this->errors, 'message' => $this->message)));
}
}
Then I tried to call the ajax from different way in js but never worked (the post query return is a message from prestashop "page not found" with http 200 response.
the doc isn't very helpful and I only find old messages/ways to do (from Prestashop 1.7.5 I'd be able to create a custom Admin controller but it doesn't work), can someone explain me the steps to follow?
thanks
Assuming it is for a PS1.7+ module, using Symphony:
Declare a link in a method of your admin controller (src/Controller/Admin) e.g
$adminLink = $this->generateUrl()
and return in with:
return $this->render
In your views/js/back.js"
$.ajax({
url: adminLink,
type: 'POST',
async: false,
data: {
},
success: (data) => {
}
});
Note: check the generateUrl and render functions for the necessary arguments.

Show login Page when user is not Authenticated

I want to authorized the request in my project and I have an issue with popuppage.On button click I have open bootstrap dialog using below code.
$('#divModalActionPage .modal-body').load(strUrl, function(e){
var html=$("#divModalActionPage .modal-body").html();
var IsvalidJSON=IsJsonString(html);
$('#divModalActionPage').modal({
backdrop: 'static',
//keyboard: false,
show: true
})
}
And strUrl action decorate with [CustomAuthorize] attribute and my CustomAuthorize contains following code.
public override void OnAuthorization(AuthorizationContext filterContext)
{
base.OnAuthorization(filterContext);
if (!filterContext.HttpContext.User.Identity.IsAuthenticated)
filterContext.Result=new ContentResult() { Content = "<script>top.window.location.href='/Home/Index'</script>" };
}
}
The issue is that when I click on the button it will go to check use is authenticated or not but not redirect me to the login page.

Cannot get json data with ajax in Razor Pages [duplicate]

This question already has answers here:
Example AJAX call back to an ASP.NET Core Razor Page
(8 answers)
Closed 5 years ago.
i am trying to get some data from Razor Pages in ASP.NET Core 2.0.
But the problem is that it does not returns any data.
I also tried debugging it, it does not fire that method (OnGetProducts) at all.
The model Index.cshtml.cs:
private IProductRepository _productRepository;
public IndexModel(IProductRepository repository)
{
_productRepository = repository;
}
public void OnGet()
{
}
public IActionResult OnGetProducts(int page)
{
var model = _productRepository.GetProducts().Skip(page * 10).Take(10);
return new JsonResult(model);
}
the razor page Index.cshtml
<div id="products">
</div>
#section scripts{
<script>
$(function () {
getProducts(0);
});
var isInitialized = false;
function getProducts(page) {
$.ajax({
type: 'GET',
url: "Products",
contentType: "application/json",
dataType: "json",
data: {
handler: 'Products',
page: page
},
success: function (datas) {
console.log(datas);
}
});
}
</script>
}
p.s. this page in in folder Pages/Products/Index.cshtml(.cs)
I usually use razor functions to generate URLs instead of hard coding them in js. If your action is not even being triggered, assuming that you are not accidentally in release mode, it is because the URL doesn't point to the right location. First of all set js variables in razor something like this:
var productsURL = #Url.Context("~/products");
Also run yourdomain/products in your browser and if you get a 404.
Alternatively I use this function to directly use c# objects in js:
public static IHtmlContent ToJS(this IHtmlHelper htmlHelper, object obj)
=> htmlHelper.Raw(JsonConvert.SerializeObject(obj));
With this function created in a static class, you can also create a js object directly something like this:
<script>
var products = #Html.ToJS(repository.GetProducts().Skip(page * 10).Take(10));
</script>
Of course this will only create the object in page load, if you want it to change after page load, you can consider creating a partial view via ajax. Also note that the second alternative will be slower than the first for ajax.

Refresh Page on Back Click - MVC 4

What would be a simple way to force my ActionResult to always fire when I hit this page? On browser back click, for instance, this will not execute.
public ActionResult Index()
{
//do something always
return View();
}
Disabling cache on the ActionResult forces the page to refresh each time rather than rendering the cached version.
[OutputCacheAttribute(VaryByParam = "*", Duration = 0, NoStore = true)]
public ActionResult Index()
{
//do something always
return View();
}
Now when you click the browsers back button, this is hit every time.
You could try the onunload event and ajax:
<script>
window.onunload = function () {
$.ajax({
url: '/ControllerName/Index',
type: 'POST',
datatype: "json",
contentType: "application/json; charset=utf-8"
});
};
</script>
Adding this code to my HTML works just fine for me:
<input id="alwaysFetch" type="hidden" />
<script>
setTimeout(function () {
var el = document.getElementById('alwaysFetch');
el.value = el.value ? location.reload() : true;
}, 0);
</script>
This might come handy for those who prefer not to deal with server side code as opposed to the accepted solution.
All it does is assign a value to a hidden input on first load which will remain on the second load in which case the page is force refreshed.

Call Ajax Play FrameWork

I have a problem with ajax, play framework 2.1.1:
My Play Project
routes:
POST /sample/testapi controllers.Application.testapi()
GET /sample/ajax controllers.Application.ajax()
Application.java
public static Result testapi() {
DynamicForm dynamicForm = DynamicForm.form().bindFromRequest();
String data= dynamicForm.get("data");
Logger.debug(data);
return ok("<user no='1'><id>1</id><name>Peter</name></user>");
}
public static Result ajax() {
return ok(ajax.render());
}
When I call action "testapi" from ajax.scala.html through ajax
My ajax code
$.ajax({
url : "http:// localhost:3333/sample/testapi",
type: 'POST',
data: {data: "test"},
dataType: "text",
success : function(result) {
alert(result);
},
error : function(request,error) {
alert(error);
}
});
It working fine.
And I have a html file and I call to play project through ajax.
The action had been called, but not return result and show alert "error".
Please help me. Thanks.
I added "response().setHeader("Access-Control-Allow-Origin", "*");" to my action.
public static Result testapi() {
response().setHeader("Access-Control-Allow-Origin", "*");
DynamicForm dynamicForm = DynamicForm.form().bindFromRequest();
String data= dynamicForm.get("data");
Logger.debug(data);
return ok("<user no='1'><id>1</id><name>Peter</name></user>");
}
"response().setHeader("Access-Control-Allow-Origin", "*");" allow other domain call it.