I have MVC project. I need to do client side validation on run time. When click the form submit button I need to hit JavaScript Method first and then it is return true move to Controller method.
Just Assume following code type:
JavaScript OnClick Method:
$(function () {
$('#btnSave').on('click', function (event) {
$.ajax({
url: '/Service/Utility/ThresholdValidation',
type: $("#addNewOrderForm").attr('method'),
data: $("#addNewOrderForm").serialize(),
success: function (data) {
if (data != "") {
event.preventDefault();
alert(data);
return false;
}
else {
return true;
}
}
});
});
});
Controller Method:
[HttpPost]
[BaseAuthenticationFilter(UserTypeEnum.Admin, PermissionEnum.CanSendRemittance)]
public ActionResult Create(Invoice model)
{
// Method Goes here
}
Here I cant popup validation alert message. When I click the button it will hit the Controller method. I need to go first javascript method and then if true go to controller method
Please help this.
Try following code, you have to return false in click handler directly instead of ajax response event. because ajax is asynchronous it will execute the ajax and call out from event handler immediately before getting the response of ajax.
So check if data not exists then submit the form otherwise show validation message
$('#btnSave').on('click', function (event) {
$.ajax({
url: '/Service/Utility/ThresholdValidation',
type: $("#addNewOrderForm").attr('method'),
data: $("#addNewOrderForm").serialize(),
success: function (data) {
if (data != "") {
alert(data);
}
else {
$("form").submit();
}
}
});
event.preventDefault();
return false;
});
Related
I am running Asp.Net Core 3.1 application where i have one left side menu in layout which i load through partial view.
To set menu link i used the anchor tag like below:
var allRouteData = new Dictionary<string, string>
{
{ "menuid", mID.ToString() },
{ "isCalledByMenu", "true" },
{ "where", "tab" }
};
<a class="#clas" data-ajax="true" data-ajax-complete="RedirectToPage('#M.MenuUrl', '#M.MenuName',true)" data-ajax-mode="replace" data-ajax-update="#myTab" asp-action="GetSubMenu" asp-controller="Base" asp-all-route-data="#allRouteData">#M.MenuName</a>
So when page loads then HTML generate like below:
<a class="nav-link btn fuse-ripple-ready" data-ajax="true" data-ajax-complete="RedirectToPage('/OrgOverview/ProfessionalServices', 'Professional Services',true)" data-ajax-mode="replace" data-ajax-update="#myTab" href="/Base/GetSubMenu?menuid=9630&isCalledByMenu=true&where=tab">Professional Services</a>
Below is action method used :
public IActionResult GetSubMenu(int menuid, bool? isCalledByMenu, string where = null)
{
return ViewComponent("SubMenu", new { menuid = menuid, isCalledByMenu = isCalledByMenu, where = where });
}
In Layout page on the top i assigned the tag helper:
#addTagHelper *, Microsoft.AspNetCore.Mvc.TagHelpers
But when i click on the link it is not hitting this action method.
Update: When i click menu then first it hit the list inside javascript where i do some ajax call:
$('#myTab>li>a.nav-link.btn.fuse-ripple-ready').on("click", function (e) {
e.preventDefault();
var requestedPage = $(this).text();
SetCurrentPageNameSession(requestedPage, false);// ajax call to set some value.
return true;
});
In SetCurrentPageNameSession method i do ajax call to set the menu name in server side to some session before calling action method.
like below:
function SetCurrentPageNameSession(CurrentPage, IsBookMark) {
if (IsBookMark==undefined)
IsBookMark = false;
var url = baseUrl+"Manage/HighlightCurrentMenu/"
$.ajax({
type: "POST",
data: { CurrentPage: CurrentPage, IsBookMark: IsBookMark },
url: url,
dataType: "json",
async:false,
success: function (data) {
var res = data.d;
},
error: function (xhr, ajaxOptions, thrownError) {
}
});
}
Then after it anchor tag call the action method.
Please suggest.
Maybe you could forget data-ajax, it also doesn't work on me and I can't find the answer about it. You could code as below and it also can request the GetSubMenu and continue to excute next logic.
<div id="myTab"></div>
<a class="nav-link btn fuse-ripple-ready"
href="#">Professional Services</a>
<script>
$('a.nav-link.btn.fuse-ripple-ready').on("click", function (e) {
//e.preventDefault();
$.ajax({
url: "/Base/GetSubMenu",
async: true,
type: "get",
datatype: "json",
data: #Json.Serialize(allRouteData),
success: function (result) {
$('#myTab').html(result)
}
});
//RedirectToPage('/OrgOverview/ProfessionalServices', 'Professional Services', true);
var requestedPage = $(this).text();
SetCurrentPageNameSession(requestedPage, false);// ajax call to set some value.
return true;
});
</script>
Comment or Remove e.preventDefault();
Calling preventDefault() during any stage of event flow cancels the event, meaning that any default action normally taken by the implementation as a result of the event will not occur.
I found the solution for the above asked question:
The issue was when i click on menu link then i used to call first it's anchor click in javascript where i did e.preventDefault() and then used to do some ajax call to pass some value to set in session. Due to e.preventDefault() call after that it was not hitting the action method.
Since i had to pass other three data to server to set somewhere. To do that i set all three value in anchor tag data-link attribute separated with Pipe like below:
data-link="9630|true|tab|/OrgOverview/ProfessionalServices|Professional Services"
function SetCurrentPageNameSession(CurrentPage, IsBookMark, MenuID, IsCalledByMenu, Where, PageUrl, PageName) {
var url = baseUrl+"Manage/HighlightCurrentMenu/"
$.ajax({
type: "POST",
data: { CurrentPage: CurrentPage, IsBookMark: IsBookMark, menuID: MenuID, isCalledByMenu: IsCalledByMenu, where: Where},
url: url,
dataType: "json",
async:false,
success: function (data) {
var res = data.d;
if (PageUrl != undefined && PageUrl != '' && PageUrl != null)
RedirectToPage(PageUrl, PageName, true, false)
},
error: function (xhr, ajaxOptions, thrownError) {
}
});
Then in this ajax call success i am redirecting the page with passed page url.
But still i am wondering the same code how it was working in MVC and not in asp.net core.
That's it.
I submit a form using ajax request. The form is actually inside a modal popup. The submission works well. But I want it to show an alert that said the form is submitted and close the current modal. Here is my code:
$('#btnBookRoom').click(function() {
$.ajax({
url: "/Booking/BookRoom",
type: "POST",
data: $('#frmRoomBooking').serialize(),
datatype: "json",
sucess: function(data) {
alert('Room Booking Success');
$('#roomBookingModal').modal('hide');
}
});
});
Controller:
public ActionResult BookRoom(RoomBookingInputModel roomBooking)
{
var domain = new RoomBooking
{
GuestId = roomBooking.GuestId
};
db.RoomBookings.Add(domain);
db.SaveChanges();
return Json(domain, JsonRequestBehavior.AllowGet);
}
The alert doest shows and the modal also not hiding.
sucess isn't a valid callback in jQuery's ajax method. You need to change it to success.
Or better, use promise API to bind a success handler (as AJAX callbacks are already deprecated):
$.ajax({ ... })
.then(function() {
alert('Room Booking Success');
$('#roomBookingModal').modal('hide');
});
I have a action method:
public ActionResult Export(int? protocol, int? visitno)
{
SetViewBagItems();
if(protocl.hasValue)
{
// code create file
if (!string.IsNullOrEmpty(csvData))
{
return File(new System.Text.UTF8Encoding().GetBytes(csvData), "text/csv", "Report.csv");
}
else
{
// need to show something in ui like, not able to create file, or any popup or any alert....
}
}
return view();
}
So in the code as mentioned, I need to show something like an alert or message when able to create the file.
Now the behavior is:
if file gets created, it will get directly downloaded and wont reload the page.
if no file is created, then the entire page will refresh.
I need to show some message instead of that.
Same controller method is used for the page to load for the first time.
How can I achieve this?
Using $.ajax() to call that function in controller. Likes:
$.ajax({
url: "/controller/action",
type: "GET",
data: {protocol: protocol, visitno: visitno},
success: function(e) {
if(e != null)
{
//Alert
}
else {
//Alert
}
}
})
You can return a JSON result from your action method as:
return Json(new {
success = true,
status = "Failure"
}, JsonRequestBehavior.AllowGet);
The ajax method from where the action method is called, check for the return status and show the error or success message in the dialog box or through alert:
$.ajax({
type: "POST",
url: "/Controller/Action",
data: { "ID": $('#id').val() },
success: function (data) {
if (data.status == "Failure")
{
$('#dialog-Add-Success').dialog({
modal: true,
opacity: 1,
buttons: {
Ok: function () {
$(this).dialog('close');
}
},
})
}
im trying to get the value each time a client selects a option from my Dropdown list to send it back to controller where i use the value on creating a file and then refreshing the page but im unable to do so
This is my Dropdownlist:
<select id="sel0">
<option value="">Todos</option>
#foreach (var item in Model.Select(l => l.Fecha).Distinct())
{
<option value="#lines">#lines</option>
}
</select>
This is my Ajax Call:
$('#sel0').on('change', function () {
dataTable.columns('.fechas').search(this.value).draw();
});
$("form").submit(function () {
$.ajax({
url: '#Url.Action("MethodName","HomePosController")',
type: 'POST',
cache: false,
data: { Selected: $("#sel0").val() },
success: function (data) {
//
}
});
});
and this is my Controller its named 'HomePosController':
public ActionResult MethodName(string Selected)
{
var db = new ArponClientPosContext();
String value = Selected;
var json4 = JsonConvert.SerializeObject(Selected);
System.IO.File.WriteAllText(#"C:\inetpub\wwwroot\potzolcalli.brain.arpon.com\valorselected.txt", json4);
return View("~/Views/HomePos/Index.cshtml", db.Pos.ToList());
}
But whenever y select a option of my dropdown nothing happens, the page its not refreshed nor the file is created what am i doing wrong?
If you want it to be on dropdown change then you have to send ajax call in change event :
$('#sel0').on('change', function () {
dataTable.columns('.fechas').search(this.value).draw();
$.ajax({
url: '#Url.Action("MethodName","HomePos")',
type: 'POST',
cache: false,
data: { Selected: $("#sel0").val() },
success: function (data) {
//
}
});
and you have to not write complete Controller class name, you have to skip the Controller postfix, it is convention which is followed by Url helpers in mvc, that way your url generated will be wrong and ajax call will fail.
whenever y select a option of my dropdown nothing happens
Well, this happens:
dataTable.columns('.fechas').search(this.value).draw();
But that doesn't invoke the AJAX request. It doesn't do much of anything, really.
how can i trigger the ajax ? i want it to trigger after a value is changed in the dropdown list
In that case you want to do that on the select element's change event. Currently you perform the AJAX request here:
$("form").submit(function () {
// AJAX
});
That is, you perform the request in the form's submit event. Just add it to the drop down's change event instead:
$('#sel0').on('change', function () {
dataTable.columns('.fechas').search(this.value).draw();
$.ajax({
url: '#Url.Action("MethodName","HomePosController")',
type: 'POST',
cache: false,
data: { Selected: $("#sel0").val() },
success: function (data) {
//
}
});
});
the page its not refreshed
Well, no. That won't happen in an AJAX request. Currently your success callback is empty, so nothing will happen on the page. Whatever you want to happen would need to be put in that callback.
I have a json data object which i need to pass from partial view to view with REDIRECT.
Lets say below is my partial view ( _createEmp.cshtml ):-
Note:- This partial view is in different view or page
<script type="text/javascript">
$(document).ready(function () {
LoadData();
});
function LoadData() {
$.ajax({
type: "GET",
url: baseURL + "Employee/GetEmpInfo",
contentType: "application/json; charset=utf-8",
dataType: "json",
async: true,
success: function (data) {
console.log(data);
**EmpData** = data; // EmpData object
},
error: function (error) {
console.log("Error: " + error);
}
});
}
</script>
<div>
<input type="submit" value="Save" onclick="SetEmpInfo()" />
</div>
And i want to transfer EmpData object to a different view (lets say NewEmp.cshtml), bind something in that view from passed "EmpData object" and open that view (or REDIRECT to view NewEmp.cshtml).
As you are using ajax, you could return the URL from your action and have it redirected in javascript.
Without seeing your controller action you would need to do something like this:
Controller
public ActionResult GetEmpInfo()
{
// Do stuff
return Json(new { success = true, redirecturl = Url.Action("GetEmpInfoSuccess") });
}
Then add something like this to your success handler in javascript:
Javascript (within your success handler)
success: function (data) {
if (data.success == true)
{
window.location = result.redirecturl;
}
}
Issuing a request to Employee/GetEmpInfo for getting the data and on success redirecting to other view - doesn't sound right
I think that you can do all this with one trip to server:
Write an Action that receives all the the parameters that GetEmpInfo receives. Lets call it NewEmployee.
If GetEmpInfo action is your code, reuse it's logic inside NewEmployee action to get EmpData. If it is not your code, you can use issue async request with HttpClient and get EmpData - All this performed on the server
Once you have EmpData you should have everything your need to return a NewEmp view.
In this particular case there is no need in AJAX at all. You can use regular form submit in case that you need to post some data or just a redirect to NewEmployee action.