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.
Related
I want to post data in the Mssql Database using Asp.netCore Api and Html Form. I have Added This script to post data.but All the values are coming null
Jquery script in Html File
<script type="text/javascript">
var valdata = $("#formData").serialize();
$(document).ready(function () {
$("#btnsubmit").click(function (e) {
let formData = {};
$("#formData").serializeArray().map((x) => { formData[x.name] = x.value; });
$.ajax({
url: "https://localhost:44389/Register",
contentType: "application/json; charset=utf-8",
type: 'POST',
dataType: 'json',
data: valdata,
success: function (data) {
alert(data);
},
failure: function (data) {
alert("Failure: " + data);
},
error: function (data) {
alert("Error: " + data);
}
});
});
});
</script>
.net Core Api
[HttpPost]
[Route("Register")]
public void RegisterExecute([FromBody]CustmRegistration Register)
{
try
{
userInterface.InsertCustomer(Register);
}
catch (Exception ex)
{
throw new Exception(ex.Message);
}
}
but All the values are coming null
Where are these values null? my suggestion is to start debugging a bit more thoroughly.
Have you tried your api function trough postman or a tool likewise?
Settting breakpoints can be nice to look into your program's data at runtime.
if these values are null in your database it would be nice to see what userInterface.InsertCustomer(Register); does.
Once you know if your .net part is working start debugging your ajaxc call. take a look at the network section of the developer tools form the browser you are using.
If you have collected more data, people can help you more easelly.
1.When you use .serialize(), it generates the data in a query string format which needs to be sent using the default contentType which is application/x-www-form-urlencoded; charset=UTF-8, not as JSON. Either remove the contentType option or specify contentType: application/x-www-form-urlencoded; charset=UTF-8 can work.
2.Also you need move the serialize method into onclick event.
3.Be sure change [FromBody] to [FromForm].
Here is a whole working demo:
View:
#model CustmRegistration
<form id="formData">
<!--more code-->
<input type="button" id="btnsubmit"value="create" />
</form>
#section Scripts
{
<script type="text/javascript">
$(document).ready(function () {
$("#btnsubmit").click(function (e) {
var valdata = $("#formData").serialize(); //move to here...
$.ajax({
url: "/home/Register",
//contentType: "application/json; charset=utf-8",
type: 'POST',
dataType: 'json',
data: valdata,
success: function (data) {
alert(data);
},
failure: function (data) {
alert("Failure: " + data);
},
error: function (data) {
alert("Error: " + data);
}
});
});
});
</script>
}
Controller:
[HttpPost]
[Route("Register")]
public void RegisterExecute([FromForm]CustmRegistration Register)
{ //...}
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 created a project in Visual Studio named 'MyProject', and Added .aspx file to it named 'MyPage.aspx'.
In 'MyPage.aspx.cs', there is a web method as shown below
[WebMethod(EnableSession=true)]
public static string GetDetails()
{
try
{
var data= HttpContext.Current.Session["mySession"] as myDto;
return myDto.Username;
}
catch
{
return "Sorry";
}
}
Now, I created another project in that same solution named 'NewProject'.
And I have a page in this project as 'NewPage.aspx', from which I am trying to call GetDetails() from 'MyPage.aspx' (MyProject).
So I tried the following code.
NewPage.aspx
<script type="text/javascript">
$(document).ready(function () {
$.ajax({
type: 'Get',
url: 'http://localhost:2463/MyPage.aspx/GetDetails',
success: function (data) {
alert(data);
},
error: function (response) {
alert('Error');
}
})
});
</script>
but the Web Method isn't getting hit & I get the 'Error' alert displayed.
I also tried this
$(document).ready(function () {
$.ajax({
type: "POST",
url: "http://localhost:2463/MyPage.aspx/GetDetails",
contentType: "application/json; charset=utf-8",
data: '{}',
datatype: "json",
success: function (msg) {
alert('success');
},
error: function (response) {
alert('Error');
}
});
});
</script>
but no luck.
Plz Help...!!
Sounds like a CORS problem.
By default you cant access a service that is not within the origin domain (scheme, hostname, port).
You have to make sure that link http://localhost:2463/MyPage.aspx/GetDetails is available while making jquery ajax call. For that
you can run MyProject in a seperate instance of VS and then run NewProject in another instance of VS.
Check console in inspect element and find a solution for given error.
You can call webMethod of another page. Your code seems correct.
And no need to write whole URL ('http://localhost:2463/MyPage.aspx/GetDetails') of a page, Just write 'MyPage.aspx/GetDetails'.
I need some help. I write little app using ASP.NET MVC4 with JavaScript and Knockout and I can't send data from javascript to MVC Controller and conversely. For example, the part of JS looks like that:
JavaScript
self.Employer = ko.observable();
self.AboutEmployer = function (id) {
$.ajax({
Url.Action("GetEmployer", "Home")
cache: false,
type: 'GET',
data: "{id:" + id + "}",
contentType: 'application/json; charset=utf-8',
dataType: "json",
success: function (data) {
self.Employer(data);
}
}).fail(
function () {
alert("Fail");
});
};
In ASP.NET MVC Home Controller I'm getting employer by ID and return it as Json:
C#
public JsonResult GetEmployer(int id)
{
var employer = unit.Repository<Employer>().GetByID(id);
return Json(employer, JsonRequestBehavior.AllowGet);
}
My View return another Controller (Home/KnockOutView). My View also gets another objects and depending what recieve, has different look:
HTML
...
<b>About Company: </b><a href="#" data-bind="click: $root.AboutEmployer.bind($data, Vacancy().EmployerID)">
<span data-bind=" text: Vacancy().Employer"></span></a>
<div data-bind="if: Vacancy">
<div id="VacancyDescription"><span data-bind="text:DescriptionShort"></span>
</div>
</div>
<div data-bind="if: Employer">
<div data-bind="text: Employer().EmployerDescription"></div>
</div>
Everything works great, I receive Vacancy and Employer objects in JS and show it in HTML using Knockout, but my URL all time still the same!!! But I want to change URL all time, when i'm getting Vacancy or Employer.
For example, if I want to get Employer, using method GetEmployer, URL should looks like that: ~/Home/GetEmployer?id=3
If I change this string of Code
Url.Action("GetEmployer", "Home") at url: window.location.href = "/home/GetEmployer?id=" + id URL will be changed, but Controller returns me an Json object and shows it in window in Json format.
Help me, please, to change URL and get information in Controller from URL.
Thanks.
Try below code, hope helps you
This code works %100 , please change below textbox according to your scenario
HTML
<input type="text" id="UserName" name="UserName" />
<input type="button" onclick="MyFunction()"value="Send" />
<div id="UpdateDiv"></div>
Javascript:
function MyFunction() {
var data= {
UserName: $('#UserName').val(),
};
$.ajax({
url: "/Home/GetEmployer",
type: "POST",
dataType: "json",
data: JSON.stringify(data),
success: function (mydata) {
$("#UpdateDiv").html(mydata);
history.pushState('', 'New URL: '+href, href); // This Code lets you to change url howyouwant
});
return false;
}
}
Controller:
public JsonResult GetEmployer(string UserName)
{
var employer = unit.Repository<Employer>().GetByID(id);
return Json(employer, JsonRequestBehavior.AllowGet);
}
Here is my controller action.
[HttpPost]
public ActionResult ActionName(string x, string y)
{
//do whatever
//return sth :)
}
and my post action is here.
<script type="text/javascript">
function BayiyeCariEkle(){
var sth= $(#itemID).text();
var sth2= $(#itemID2).text();
$.post("/ControllerName/ActionName", { x: sth, y: sth2});
}
</script>
use data parameters like this {id:id, otherPara:otherParaValue}
$.ajax({
url:Url.Action("GetEmployer", "Home")
type: 'GET',
data: {id:id},
contentType: 'application/json; charset=utf-8',
dataType: "json",
success: function (data) {
alert(data)
}
});
Due to MVC being slightly annoying in it's processing of routes to the same view, I've had success doing this:
self.Employer = ko.observable();
self.AboutEmployer = function (id) {
$.ajax({
url: "#Url.Action("GetEmployer", "Home", new { id = "PLACEHOLDER"})".replace("PLACEHOLDER", id),
cache: false,
type: 'GET',
contentType: 'application/json; charset=utf-8',
dataType: "json",
success: function (data) {
self.Employer(data);
}
}).fail(
function () {
alert("Fail");
});
};
You can use standard url: "#Url.Action("GetEmployer", "Home")/" + id, but on refresh, the route with the existing ID stays in subsequent calls, so it begins appending the id, which obviously doesn't work. By specifying the ID in call, that behavior is no longer present.
The best way for navigation on my opinion, is to use sammy.js. Here is a post about that kazimanzurrashid.com
How can I call the same action using ajax from different pages?
type: 'POST',
url: 'Notification/GetRecentNotifications/'
I'm currently using the code above to call my action. It works for my application's home page, but when I change to other page, this doesn't work. Can anybody give me a solution? Thanks before.
Heres what I usually do to point to which controller & action to call within an ajax jquery call...
$.ajax({
type: "POST",
url: '#(Url.Action("Action", "Controller"))',
success: function (data) {
}
});
Use Url.Action() to build links
Put the code in a ajax.js file in your scripts directory then reference it in the pages where you need to use the methods in that file. Then, put any server side logic for your ajax calls in an AjaxController For example:
ajax.js
function foo() {
var model = { };
$.ajax({
url: '#Url.Action("Foo", "Ajax")',
type: "POST",
data: JSON.stringify(model),
success: function(data) {
alert(data);
},
error: function(data) {
alert(data);
}
});
}
AjaxController.cs
public class AjaxController : Controller
{
[HttpPost]
public JsonResult Foo(FooModel model)
{
string message = _ajaxService.Foo(model);
return Json(message);
}
}
In the example above _ajaxService is a service layer object that contains the logic to handle your ajax requests. Below is how to use the function in your view:
SomeView.cshtml
<script type="text/javascript" language="javascript" src="#Url.Content("~/Content/Scripts/ajax.js")"></script>
<script type="text/javascript" language="javascript">
$(document).ready(function () {
$('#button').click(foo);
});
</script>
If there is additional logic to pass data to the ajax method that is reused, you should probably put it in a partial view and reference that from every view that needs it.