I have created a button to pass some parameters to a controller and get the response in a responsive pop-up.
But somehow when I click the button, nothing happens. No error in Dev.Option (F12), and I already make sure the parameter goes into my controller.
My reference : http://aspsnippets.com/Articles/Open-Show-jQuery-Dialog-Modal-Popup-after-AJAX-Call-Success.aspx
I'm using MVC C# on Visual Studio 2010. Below is my code:
My home page, all pre-requisite Jquery are already automatically reloaded inside global.asax.
HomePage.cshtml
var externalID = "123";
var susbcrNo = "456";
<a href="#COV" onclick="javascript:CustomerOneView.displayPopUpWindow(#externalID, #susbcrNo);" >DETAILS</a>
<div id="dialog" style="display: none"/>
#section Scripts{
<script type="text/javascript" src="#Url.Content("~/Scripts/CustomerOneView.js")" ></script>
<script type="text/javascript">
$("#dialog").dialog({
autoOpen: false,
modal: true,
title: "Details",
buttons: {
Close: function () {
$(this).dialog('close');
}
}
});
Inside CustomerOneView.js :
var CustomerOneView = (function () {
return {
init: function () {
},
displayPopUpWindow: function (externalID, susbcrNo) {
var postData = {
externalID: externalID,
susbcrNo: susbcrNo
};
$.ajax({
type: "POST",
url: "/Home/OneViewDetails",
data: JSON.stringify(postData),
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (r) {
$("#dialog").html(r);
$("#dialog").dialog("open");
}
});
}
};
})();
$(document).ready(function () {
CustomerOneView.init();
});
My controller :
[HttpPost]
public JsonResult OneViewDetails(string externalID, string susbcrNo)
{
Models deviceDetails = new Models();
deviceDetails.Code = externalID;
deviceDetails.Message = susbcrNo;
// call log here make sure the values.
Logger.Debug("COV called here " + externalID + " - " + susbcrNo);
// old return
// return Json(deviceDetails, JsonRequestBehavior.DenyGet);
return Json(deviceDetails);
}
My Controller is already tied into a view that supposed to be a pop-up view. Let's call it PopUp.cshtml
How can I fix this issue?
I need to clarify something about C# on the server side; if you return a value on a function/method, it will return the value to the code that called said function/method as opposed to intelligently guessing that you want to print the value back to the client so the browser may then manipulate the results?
If that is the case, you need to echo or print the return value from the function/method or from where the function/method is called.
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 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.
I have following code which is making an Ajax call from a .CSHTML file.
<script type="text/javascript">
$("#Save").click(function () {
var model = {
EmployeeId: #Model.EmployeeId,
OverrideTermDate: $('#OverrideTermDate').val(),
OverrideHireDate: $('#OverrideHireDate').val(),
};
$.ajax({
data: #Model.EmployeeId,
url: "/Employee/UpdateOverrideDates",
type: "POST",
success: function (result) {
$(function () {
$("#dialog").dialog();
});
}
});
});
</script>
My VS shows syntax error. But instead of #Model.EmployeeId if I hardcode it to any int value like 1 then it works fine.
Now #Model.EmployeeId is not NULL and it is an int. It is just that Ajax does not like it. Any idea why? Should I not be using #Razor components in Ajax calls?
To use Razor in JS, wrap the attributes in '',
data : '#Model.EmployeeId',
//For passing integer use parseInt('#Model.EmployeeId') or Number('#Model.EmployeeId')
and
var model = {
EmployeeId: '#Model.EmployeeId',
....
};
The quotes act as delimiters, so the Razor parser recognizes the values.
or Alternatively,
data : #Model.EmployeeId + "",
It's just a bug in Visual Studio, the view should works as excepted.
The answer was explained here: Razor/JavaScript and trailing semicolon.
If you don't like it, you can just put the "plus zero" after the #Model
$("#Save").click(function () {
var model = {
EmployeeId: #Model.EmployeeId + 0,
OverrideTermDate: $('#OverrideTermDate').val(),
OverrideHireDate: $('#OverrideHireDate').val(),
};
$.ajax({
data: #Model.EmployeeId + 0,
url: "/Employee/UpdateOverrideDates",
type: "POST",
success: function (result) {
$(function () {
$("#dialog").dialog();
});
}
});
});
I want to display data in a table based on the search criteria in a textbox. I have implemented it without using Ajax but do not know how to call controller method using jquery and update table data. Please try to solve my problem. Thanks...
Index.cshtml
#model IEnumerable<MvcApplication4.Models.tbl_product>
#{
Layout = null;
}
<!DOCTYPE html>
<html>
<head>
<script src="#Url.Content("~/Scripts/jquery-1.5.1.js")" type="text/javascript"></script>
<title>Index</title>
<script type="text/javascript">
$(document).ready(function () {
$('#Button1').click(function () {
alert("button clicked");
$.ajax({
type: 'POST',
contentType: "application/json; charset=utf-8",
url: 'Home/Index',
data: "{'searchString':'" + document.getElementById('searchString').value + "'}",
async: false,
Success: function (response) {
alert("Success");
window.location.reload();
},
error: function () { alert("error"); }
});
});
});
</script>
</head>
<body>
#* #using (#Html.BeginForm("Index", "Home"))
{*#
#Html.TextBox("searchString");
<input type="button" value="filter" id="Button1" />
#* }*#
<table id="showData">
#{Html.RenderPartial("SearchList");}
</table>
</body>
</html>
SearchList.cshtml(Partial View)
#foreach (var item in Model)
{
<tr>
<td>#item.ProductName</td>
<td>#item.ProductId</td>
<td>#item.ProductDesc</td>
</tr>
}
HomeController.cs
public class HomeController : Controller
{
//
// GET: /Home/
ProductEntities dbentity = new ProductEntities();
public ActionResult Index()
{
return View(dbentity.tbl_product.ToList());
}
[HttpPost]
public ActionResult Index(string searchString)
{
var query = dbentity.tbl_product.Where(c => c.ProductName.Contains(searchString));
return View(query.ToList());
}
}
$.ajax({
url: '/ControllerName/ActionName',
type: "POST",
data: {criteria: 'criteria'},
contentType: "application/json",
success: function (data) {
//Replace existing table with the new view (with the table).
}
});
//write ControllerName without the key controller.
$.ajax({
type: 'POST',
contentType: "application/json; charset=utf-8",
url: 'Home/Index',
data: JSON.stringify({'searchString':document.getElementById('searchString').value }),
async: false,
Success: function (response) {
alert("Success");
//append the data in between table tbody like,
$('table tbody').html(response);
//No window.location.reload(); It will cause page reload initial data will appear in grid.
},
error: function () { alert("error"); }
});
return false
Hope this helps.
Your ajax request should look like:
$.ajax({
url: '/<ControllerName>/<MethodName>',
type: "POST",
data: requestData,
contentType: "application/json;charset=utf-8",
success: function (data, textStatus, XMLHTTPRequest) {
//Success callback handling
},
error: function (XMLHTTPRequest, textStatus, errorThrown) {
//Error callback handling
},
cache: false //whether you want to cache the response or not.
});
I'm not going to give you the exact answer, but to help you to get it.
There are two steps:
First you must get sure the request is being done, and the response is being get on the browser.
To do so, you can
do it on your way: leave only the alert("Success"); and check it's being run.
better than that, open the browser's developer console (I prefer Chrome, but you can also use IE or FireFox + FireBug add-on) using F12. Set breakpoints and inspect variable values and code flow. See thit tutorial for Chrome developer tools.
set a breakpoint on the server action, and check it's executed
Second Once you're sure the firs part is working fine, use your succes function to replace the table content with the data received in the response. You can do it in several ways with jQuery. For example
$('#showData').html(response);
Again, you can execute this code and inspect the contents of response from the developer's console in your browser. This makes things eaiser when you're starting to use javascript.
(If your action generated the whole table, you could use jQuery's replaceWith which replaces the target, instead of its content. Don't use this for this case).
FINAL NOTE: please, remove this code window.location.reload();!!! This reloads the whole page with the current URL, so whatever thing you do in advance will be lost.
I have ah HTML5 form with an action defined as follows:
#using (Html.BeginForm("SearchAction", "ResultsController"))
The form takes in two text fields:
<input type="text" name="txtSearchTerm" id="txtSearchTerm" class="frontPageInput" placeholder="Begin your search..." required />
<input type="text" name="txtGeoLocation" id="txtGeoLocation" class="frontPageInput" required />
The txtGeoLocation field is an autocomplete field that is fed from a cached object, fed through the controller and by a model repository class through the following jQuery code:
<script type="text/javascript" language="javascript">
$(function () {
$("#txtGeoLocation").autocomplete(txtGeoLocation, {
source: function (request, response) {
$.ajax({
url: "/home/FindLocations", type: "POST",
dataType: "json",
selectFirst: true,
autoFill: true,
mustMatch: true,
data: { searchText: request.term, maxResults: 10 },
success: function (data) {
response($.map(data, function (item) {
return { label: item.GeoDisplay, value: item.GeoDisplay, id: item.GeoID }
}))
}
})
},
select: function (event, ui) {
alert(ui.item ? ("You picked '" + ui.item.label + "' with an ID of " + ui.item.id)
: "Nothing selected, input was " + this.value);
document.getElementById("hidLocation").value = ui.item.id;
}
});
});
There's an alert there for debugging. When clicking on the text that drops down, this alert fires, however it does not fire if you type in the whole word and hit submit.
I would like to first, validate the text in the geo text box on the client side, to ensure that it is a value contained in the collection, of not, have the text box in red, communicate that.
Thanks.
You can use jquery remote validation using the [Remote()] attribute to validate the value is in the list. You will have to do the same check on the server side when you post back as well.