ASP.Net MVC + Autocomplete Search not working - c#

I'm a beginner & I'm trying to develop a autocomplete search box with ASP.Net MVC 5. I use Northwind Database and Entity Framework 6.
Here is my index.cshtml code
#model IEnumerable<AutoComplete3.Models.Customers>
<link href="~/Content/jquery-ui.css" rel="stylesheet" />
<script type="text/javascript" src="~/Scripts/jquery-1.9.1.js"></script>
<script type="text/javascript" src="~/Scripts/jquery-ui.js"></script>
<script type="text/javascript">
$(function () {
$("#txtSearch").autocomplete({
source: '#Url.Action("GetCustomers")'
});
});
</script>
#using (#Html.BeginForm())
{
<b>Name : </b>
#Html.TextBox("searchTerm", null, new { #id = "txtSearch" })
<input type="submit" value="Search" />
}
Here is my CustomerController class
public class CustomersController : Controller
{
northwindEntities db = new northwindEntities();
public ActionResult Index()
{
return View(db.Customers);
}
[HttpPost]
public ActionResult Index(string SearchTerm)
{
List<Customers> customers;
if (string.IsNullOrEmpty(SearchTerm))
{
customers = db.Customers.ToList();
}
else
{
customers = db.Customers.Where(c => c.CompanyName.StartsWith(SearchTerm)).ToList();
}
return View(customers);
}
public JsonResult GetCustomers(string term)
{
List<string> customers;
customers = db.Customers.Where(c => c.CompanyName.StartsWith(term)).Select(y => y.CompanyName).ToList();
return Json(customers,JsonRequestBehavior.AllowGet);
}
}
This code is working when i am searching records, by entering keyword & clicking submit button. But the GetCustomer method cannot be called by the jquery script. Inspect Elements shows following error.
Uncaught TypeError: $(...).autocomplete is not a function
The text box should be suggest Company Names to the textbox itself. How to correct this.
Thanks.

Javascript
$(document).ready(function () {
$("#txtSearch").autocomplete({
source: function (request, response) {
$.ajax({
url: '#Url.Action("GetCustomers","Home")',
type: "POST",
dataType: "json",
data: { searchTerm: request.term },
success: function (data) {
response($.map(data, function (item) {
return { label: item.CompanyName, value: item.CompanyName };
}))
}
})
},
messages: {
noResults: "", results: ""
},
});
})
View
#using (#Html.BeginForm())
{
<b>Name : </b>
#Html.TextBox("searchTerm", null, new { #id = "txtSearch" })
<input type="submit" value="Search" />
}
Controller
Please update your controller with [HttpPost]
[HttpPost]
public JsonResult GetCustomers(string searchTerm)
{
List<string> customers;
customers = db.Customers.Where(c => c.CompanyName.StartsWith(term)).Select(y => y.CompanyName).ToList();
return Json(customers,JsonRequestBehavior.AllowGet);
}

Related

.Net Core 3.1 fails to bind properties while using ajax call before submitting the page

I'm using .net core 3.1 razor pages. I have a page with a property. I'm using a jQuery ajax call in my page. Sometimes though my field was filled, but the property got null in my PostAsync method. After spending much time, I found that MyProperty was null (not bound) when I called my $.ajax function in the page before submitting it! Is it a bug in .net core or have I forgotten some settings?
MyPage.chtml:
...
<form method="post">
My Property: <input asp-for="MyProperty" /><br />
<button id="doAction" type="button">Do some action in server</button><br />
<button type="submit">Submit</button>
</form>
<script>
$(document).ready(function() {
$('#doAction').click(function(){
$.ajax(
'/api/myaction/doSomeAction/2',
{
type: 'POST',
success: function() { alert('Some action done successfully.'); }
}
});
});
</script>
...
MyPage.chtml.cs:
[BoundProperty]
public string MyProperty { get; set; }
...
public async Task<IActionResult> OnPostAsync()
{
var temp = MyProperty;
...
}
MyAction controller class:
[Route( "api/[controller]" )]
[ApiController]
public class MyActionController : Controller
{
[HttpPost( "doSomeAction/{code?}" )]
public async Task<dynamic> PostAsync( int code )
{
// do some actions...
}
}
Startup.cs:
public void Configure( IApplicationBuilder app , IWebHostEnvironment env )
{
...
app.UseEndpoints( endpoints =>
{
endpoints.MapRazorPages();
endpoints.MapControllerRoute( "default", "{controller}/{action}/{id?}" );
} );
...
}
Scenarios:
Fill MyProperty with "MyValue" and submit form => MyProperty == "MyValue" (OK).
Fill MyProperty with "MyValue"; click doAction button; then submit form => MyProperty == null (binding property failed!)
I don't know exactly where your problem is, but this kind of error will not occur under normal circumstances. You can see my working example below.
Index.chtml:
#page
#model xxxxx.IndexModel
#addTagHelper *, Microsoft.AspNetCore.Mvc.TagHelpers
#Html.AntiForgeryToken()
#{
Layout = "_Layout";
}
<form method="post">
My Property: <input asp-for="MyProperty" /><br />
<button id="doAction" type="button">Do some action in server</button><br />
<button type="submit">Submit</button>
</form>
#section scripts{
<script>
$(document).ready(function () {
$('#doAction').click(function () {
$.ajax(
{
url: '/api/myaction/doSomeAction/2',
type: 'POST',
beforeSend: function (xhr) {
xhr.setRequestHeader("XSRF-TOKEN",
$('input:hidden[name="__RequestVerificationToken"]').val());
},
success: function () { alert('Some action done successfully.'); }
})
});
});
</script>
}
In your startup,add:
//...
services.AddAntiforgery(o => o.HeaderName = "XSRF-TOKEN");
Index.chtml.cs:
[BindProperty]
public string MyProperty { get; set; }
public void OnGet()
{
}
public IActionResult OnPost()
{
//...
return Page();
}
MyAction controller class:
[Route("api/[controller]")]
[ApiController]
public class MyActionController : ControllerBase
{
[HttpPost("doSomeAction/{code?}")]
public async Task<dynamic> PostAsync(int code)
{
return "Ok";
}
}
Test Result:
you suppose to be sending data into your ajax post call,
<script>
$(document).ready(function() {
<script>
$(document).ready(function() {
$('#doAction').click(function(){
$.ajax(
'/api/myaction/doSomeAction/2',
{
type: 'POST',
data:$(form).serializeArray();
success: function() { alert('Some action done successfully.'); }
}
});
});
</script>

C# : Calling controller method from view folder

I'm totally a noob to MVC Framework. And I want to call my Agentcontroller's action method which is in the Controller folder.
I'm trying to call
Controller/Agentcontroller/myactionmethod()
from View Folder
View/Agent/CodeGenerate.cshtml
I think I'm having trouble with the route but I can't find the App_Start folder. This is the script I'm using.
<script type="text/javascript">
function G() {
$.ajax({
type: "post",
url: '/AgentsControllers/',
data: $('form').serialize(),
success: function (response) {
alert("Hi");
}
});
}
</script>
I've also checked this out as well: MVC - calling controller from view
Thanks in advance!
Your Ajax call should be :
<script type="text/javascript">
function G() {
$.ajax({
type: "post",
url: '/AgentsControllers/myactionmethod/',
data: $('form').serialize(),
success: function (response) {
alert("Hi");
}
});
}
</script>
And your Controller Action Method Should be :
[HttpPost]
public ActionResult myactionmethod(YourModelName objYourModelobject)
{
return PartialView("~/Views/Agent/CodeGenerate.cshtml", objYourModelobject);
}
And Your View Should be :
#model Application.Model.YourModel
#using (Html.BeginForm("Agentcontroller", "myactionmethod", FormMethod.Post, new { #class = "example" }))
{
//HTML Helpers
#Html.HiddenFor(model => model.Id, new { #id = "hdnDetailId" })
<button type="submit" class="btn btn-success" id="btnSave"><i class="fa fa-floppy-o"></i> Save</button>
}

jquery click method is not attached to button

I have asp.net mvc 5 application but I can't get this fairly simple script to work. I am new to this MVC (I am WebForms guy).
Basically jQuery is not attaching .click() event to the button to post data to the underlying controller.
Can somebody pinpoint what I am doing wrong?
The View (HelloWorld/Index.cshtml):
#model HelloWorld.Models.HelloWorldModel
<!DOCTYPE html>
<html>
<head>
<title>Hello World</title>
<script src="~/Scripts/jquery-2.1.3.min.js"></script>
</head>
<body>
<div>
#using (Html.BeginForm("Welcome","HelloWorld",FormMethod.Post, new {id = "myhelloform"})){
<span>Name:</span>
#Html.TextBoxFor(model=> model.Name)
<button id="btnPost" type="button">Post</button>
}
</div>
<script>
var testform = function () {
var init = function () {
$("#btnPost").on("click", function () {
alert("anybody there??");
submitForm();
});
};
var submitForm = function () {
$.hit({
url: "#Url.Action("Welcome", "HelloWorld")",
data: $("#myhelloform").serializeArray(),
success: function (response) {
alert(response.Message);
}
});
};
return {
Init: init
};
};
</script>
</body>
</html>
</html>
The Controller (Controllers/HelloWorldController.cs):
using System.Web.Mvc;
namespace HelloWorld.Controllers
{
public class HelloWorldController : Controller
{
public ActionResult Index()
{
return View();
}
[HttpPost]
public JsonResult Welcome()
{
return Json("test");
}
}
}
The Model (Models/HelloWorldModel.cs)
namespace HelloWorld.Models
{
public class HelloWorldModel
{
public string Name { get; set; }
}
}
Delete the variables testform and init and it works (Also need to use $( document ).ready as #Tbseven mentions):
$( document ).ready(function() {
$("#btnPost").on("click", function ()
{
alert("anybody there??");
});
});
Fiddle: https://dotnetfiddle.net/HCdFXM
You have to place your jquery code inside next function:
$( document ).ready(function() {
// Here
});
$( document ).ready(function() {
$("#btnPost").on("click", function () {
alert("anybody there??");
submitForm();
});
function submitForm () {
$.hit({
url: "#Url.Action("Welcome", "HelloWorld")",
data: $("#myhelloform").serializeArray(),
success: function (response) {
alert(response.Message);
});
};
});
You can use input instead of button and there is no need to add click event for that.
<input type="submit" id="btnPost" />

Not able to see Kendo Grid the output

I was working to use Kendo Grid in asp.net mvc4.Here is the code written in contrller and view.But i am not getting the Kendo Grid in output.Can anyone help me with this?
I have used ADO.NET entity model to form class called Contacts to connect to the database
and in the controller i have converted the data coming from Contacts class to json.
Controller:
public class HomeController : Controller
{
public PersonaEntities db = new PersonaEntities();
public ActionResult Index()
{
return View();
}
[AllowAnonymous]
[HttpGet]
public JsonResult Getjsondata()
{
ViewBag.Title = "Hello World";
JsonResult jsonResult = new JsonResult();
var Contacts = db.Contacts.ToList();
jsonResult.Data = Contacts;
return Json(jsonResult,JsonRequestBehavior.AllowGet);
}
Then i have tried in the view to display kendo grid by giving its datasource as controller action method.But I am not getting the output as kendo grid.
View:
#{
ViewBag.Title = "Getjsondata";
}
<h2>Getjsondata</h2>
<link href="~/Content/kendo/2014.2.716/kendo.common.min.css" rel="stylesheet" type="text/css" />
<link href="~/Content/kendo/2014.2.716/kendo.default.min.css" rel="stylesheet" type="text/css" />
<link href="~/Content/kendo/2014.2.716/kendo.dataviz.min.css" rel="stylesheet" type="text/css" />
<link href="~/Content/kendo/2014.2.716/kendo.dataviz.default.min.css" rel="stylesheet" />
<script src="~/Scripts/kendo/2014.2.716/angular.min.js"></script>
<script src="~/Scripts/kendo/2014.2.716/jquery.min.js"></script>
<script src="~/Scripts/kendo/2014.2.716/kendo.all.min.js"></script>
<script>
$(document).ready(function () {
var dataSource = new kendo.data.DataSource({
transport: { read: { url: "Home/Getjsondata", dataType: "json" } },
schema: {
data: function (data) {
return data;
}
}
})
$("#Grid").kendoGrid({
dataSource: dataSource,
columns: [
{
field: "id",
title: "id"
},
{
field: "fname",
title: "fname"
},
{
field: "lname",
title: "lname"
},
{
field: "phone",
title: "phone"
}
]
});
});
</script>
<div id="Grid"></div>
The Json method encapsulated the data into a JsonResult already. Your reposonse is double-wrapped. Pass the data directly into the Json method.
You'll need two actions, one for the static view and one for the JsonResult:
public class HomeController : Controller
{
public ActionResult GridView()
{
return this.View();
}
public JsonResult Getjsondata()
{
var Contacts = db.Contacts.ToList();
return Json(Contacts, JsonRequestBehavior.AllowGet);
}
}
For the view, you need a GridView.cshtml:
#* css and js imports omitted *#
<script>
$(document).ready(function () {
$("#Grid").kendoGrid({
dataSource: {
type: "json",
transport: {
read: {
url: '#Url.Action("Getjsondata")',
type: 'GET', // should be POST, though
}
},
schema: {
type: "json",
model: {
id: "id",
fields: {
'id' : { type: 'number', editable: false},
'fname': { type: 'string' },
'lname': { type: 'string' },
'phone': { type: 'string' }
}
}
}
},
columns: [
{
field: "id",
title: "id"
},
{
field: "fname",
title: "fname"
},
{
field: "lname",
title: "lname"
},
{
field: "phone",
title: "phone"
}
]
});
});
</script>
<div id="Grid"></div>
The url of the page is ~/Home/GridView. When you open the page, the controller only returns the static page GridView.cshtml. Once the page is loaded on the client side (your browser), the JavaScript code will run and make an AJAX request to the ~/Home/Getjsondata action to load the data for the kendo grid.
I found out that i was loading the script jquery.js manually which i think gets loaded by default in browser.Also i found that scripts and css files need to be mentioned only in shared layout file and not necessary to mention it in view.
jquery asp.net-mvc

MVC 3 Ajax.ActionLink understand something

so Iam new on this and I have a Ajax.ActionLink that work fine but can't understand (why I have to put the div "linkEdit" in my list view and in the partial view)
so have Ajax.ActionLink in my list view of solution (and when select a solution it get me all the product) and it goes to a action to
[HttpGet]
[Ajax(true)]
[ActionName("Index")]
public ActionResult Index_Ajax(Int32? id)
{
// to do = load the product that solution have
return PartialView("SolutionProduct", viewModel);
}
the Ajax.ActionLink
#Ajax.ActionLink("Select", "Index", "solution",
new { id = item.solutionId },
new AjaxOptions
{
HttpMethod = "GET",
UpdateTargetId = "linkEdit",
InsertionMode = InsertionMode.Replace
})|
i have this div in a partial view "SolutionProduct" and in my list view
<div id="linkEdit">
<table>
<tr>
<th>Nombre de Producto</th>
</tr>
#foreach (var item in Model.Productos)
{
<tr >
<td>
#item.Nombre
</td>
</tr>
}
</table>
}
</div>
so my question would be why if I take out the div on my list view it doesnt work?
I am going to share here different examples of using AJAX in ASP .NET MVC 4.
1) Use an Internet Application template to create ASP .NET MVC 4 project in Visual Studio 2012.
2) Under the folder Models create this simple class
public class Person
{
public string FirstName { set; get; }
}
3) Add following code to public class HomeController : Controller
[AcceptVerbs("POST")]
public bool MethodWithoutParameters()
{
bool allow = true;
if (allow)
{
return true;
}
else
{
return false;
}
}
[AcceptVerbs("POST")]
public string MethodWithParameters(string id)
{
return id + " i got it, man! ";
}
[AcceptVerbs("GET")]
public ActionResult GetSomeName()
{
var data = new { name = "TestName " };
return Json(data, JsonRequestBehavior.AllowGet);
}
[AcceptVerbs("POST")]
public ActionResult PerformAction(FormCollection formCollection, Person model)
{
model.FirstName += "Well done! Form 1";
return Json( model.FirstName);
}
[AcceptVerbs("POST")]
public ActionResult PerformAction2(FormCollection formCollection, Person model)
{
model.FirstName += "Well don! Form 2";
return Json(model.FirstName);
}
public JsonResult DeleteFile(string fileName)
{
var result = fileName + " has been deleted";
return Json(result, JsonRequestBehavior.AllowGet);
}
4) Replace all code within Index.cshtml with the following one (Perhaps, instead of MvcApplication1 you have to use your real application name...)
#model MvcApplication1.Models.Person
#{
ViewBag.Title = "Home Page"; } #section featured {
}
MethodWithoutParameters
MethodWithParameters
'parameter00001'
#using (Ajax.BeginForm("PerformAction", "Home", new AjaxOptions {
InsertionMode = InsertionMode.Replace, HttpMethod = "POST", OnSuccess
= "OnSuccess", OnFailure = "OnFailure" })) {
This is a demo form1.
#Html.LabelFor(model => model.FirstName)
#Html.TextBoxFor(model => model.FirstName, null, new { #class = "labelItem" })
}
#using (Ajax.BeginForm("PerformAction2", "Home", new AjaxOptions {
InsertionMode = InsertionMode.Replace, HttpMethod = "POST", OnSuccess
= "OnSuccess2", OnFailure = "OnFailure2" })) {
This is a demo form2.
#Html.LabelFor(model => model.FirstName)
#Html.TextBoxFor(model => model.FirstName, null, new { #class = "labelItem" })
}
cat.png
Delete File
function DeleteFile() {
var fn = $('#fileNameLabel').html();
$.ajax({
url: "Home/DeleteFile", //check this.href in debugger
dataType: "text json",
type: "POST",
data: { fileName: fn }, //pass argument here
success: function (data, textStatus) {
if (data) {
if (textStatus == 'success') {
$('#fileNameLabel').html(data);
$('#btnDeleteFile').hide();
}
else {
alert('error');
}
} else {
alert('error');
}
}
});
}
function OnSuccess(response) {
$('#form1').html(response);
}
function OnFailure2(response) {
alert("Error Form 2");
}
function OnSuccess2(response) {
$('#form2').html(response);
}
function OnFailure(response) {
alert("Error Form 1");
}
function MethodWithoutParameters() {
var url = "Home/MethodWithoutParameters";
$.post(url, function (data) {
if (data) {
alert(data);
} else {
alert('error');
}
});
}
function MethodWithParameters(id) {
var url = "Home/MethodWithParameters/" + id;
// alert(url);
$.post(url, function (data) {
if (data) {
alert(data);
} else {
alert('error');
}
});
}
$(document).ready(function () {
$.getJSON("Home/GetSomeName",
null,
function (data) {
if (data) {
$('#UserNameLabel').html(data.name);
} else {
alert('error');
}
}
);
}); </script>
5) Make sure that header of the _Layout.cshtml looks like
<meta charset="utf-8" />
<title>#ViewBag.Title - My ASP.NET MVC Application</title>
<link href="~/favicon.ico" rel="shortcut icon" type="image/x-icon" />
<meta name="viewport" content="width=device-width" />
#Styles.Render("~/Content/css")
#Scripts.Render("~/bundles/modernizr")
#Scripts.Render("~/bundles/jquery")
<script src="#Url.Content("~/Scripts/jquery.unobtrusive-ajax.js")"
type="text/javascript">
6) And everything should work fine.
I hope all those samples will help you!
You have to put the div with an id of "linkEdit" into your list view as that is the portion of the page that is to be replaced by the result returned by the ajax link.
ASP.NET AJAX enables a Web application to retrieve data from the server asynchronously and to update parts of the existing page. This improves the user experience by making the Web application more responsive.
And is this case you are using the InsertionMode
InsertionMode = InsertionMode.Replace
so you will need a div with the id of "linkEdit" in both your list view and partial view.

Categories

Resources