Autocomplete for textbox in mvc - json

This is my view and controller. I have converted code from c# to vb the code was working perfectly in C# but i dont know why this java script is not working in vb. I started debugging but controllers never get called when i type something in search box.
Code for View
#ModelType PrudentHealthCare.Product
#Code
Layout = Nothing
End Code
<!DOCTYPE html>
<html>
<head>
<meta name="viewport" content="width=device-width" />
<title>Search</title>
</head>
<body>
<div>
#Using (Html.BeginForm())
#Html.HiddenFor(Function(model) model.id)
#<input type="text" id="search" placeholder="Search for a product" required />
#<input type="submit" value="Go" id="submit" />
End Using
</div>
</body>
</html>
<link href="~/Content/AutoComplete/jquery-ui.css" rel="stylesheet" />
<script src="~/Content/AutoComplete/jquery-ui.js"></script>
<script src="~/Content/AutoComplete/jquery-1.9.1.js"></script>
<script type="text/javascript">
var url = '#Url.RouteUrl( "DefaultApi" , New With { .httproute = "", .controller = "ProductApi" })';
$('#search').autocomplete({
source: function (request, response) {
$.ajax({
url: url,
data: { query: request.term },
dataType: 'json',
type: 'GET',
success: function (data) {
response($.map(data, function (item) {
return {
label: item.Description,
value: item.Id
}
}));
}
})
},
select: function (event, ui) {
$('#search').val(ui.item.label);
$('#Id').val(ui.item.value);
return false;
},
minLength: 1
});
</script>
ProductApiController
Imports System.Web.Mvc
Namespace Controllers
Public Class ProductApiController
Inherits Controller
<HttpGet>
Public Function GetProducts(Optional query As String = "") As IEnumerable(Of Product)
Dim xyz As String
xyz = query
End Function
End Class
End Namespace

jQuery UI has an AutoComplete widget. The autocomplete widget is quite nice and straight forward to use. In this post, how to integrate the AutoComplete widget with an ASP.NET MVC application.
The first step is to add the jQuery scripts and styles. With ASP.NET MVC 4, the following code does the work:
#Styles.Render("~/Content/themes/base/css")
#Scripts.Render("~/bundles/jquery")
#Scripts.Render("~/bundles/jqueryui")
Using the AutoComplete widget is also simple. You will have to add a textbox and attach the AutoComplete widget to the textbox. The only parameter that is required for the widget to function is source. For this example, we will get the data for the AutoComplete functionality from a MVC action method.
$(document).ready(function () {
$('#tags').autocomplete(
{
source: '#Url.Action("TagSearch", "Home")'
});
})
In the above code, the textbox with id=tags is attached with the AutoComplete widget. The source points to the URL of TagSearch action in the HomeController: /Home/TagSearch. The HTML of the textbox is below:
<input type="text" id="tags" />
When the user types some text in the textbox, the action method - TagSearch is called with a parameter in the request body. The parameter name is term. So, your action method should have the following signature:
public ActionResult TagSearch(string term)
{
// Get Tags from database
string[] tags = { "ASP.NET", "WebForms",
"MVC", "jQuery", "ActionResult",
"MangoDB", "Java", "Windows" };
return this.Json(tags.Where(t => t.StartsWith(term)),
JsonRequestBehavior.AllowGet);
}

Related

How can I define a route for search process in ASP.NET MVC?

I have a problem about defining a route with respect to a search process in the controller part of ASP.NET MVC.
What I want to do is to get this URL which is defined below after I click a search button in the form.
Blog/Search?searchKeyword=banana
I created a sample form but I have no idea how to define the url in its action. How can I do that?
Here is the code related with a form code snippet which is shown below.
<form action="Blog/Search/" method="get">
<input type="text" name="searchKeyword">
<button type="submit"><i class="bi bi-search"></i></button>
</form>
Here is the search function which is defined in the controller part shown below.
[HttpGet]
[Route("Blog/Search/{searchKeyword}")]
public ActionResult BlogSearch(string search_string, int Sayfa = 1)
{
var searchList = db.Blog.Include("Category").Where(
x => x.Content.Contains(search_string)).OrderByDescending(x => x.BlogId).ToPagedList(Page, 5);
return View(searchList);
}
Here is my answer shown below.
js file
<script type="text/javascript">
$(document).ready(function () {
$("#searchButton").click(function () {
var searchKeyword = $("#searchKeyword").val();
$.ajax({
url: '/Home/BlogSearch/',
data: {searchKeyword: searchKeyword},
type: 'POST'
});
});
})
</script>
BlogSearch Process
public ActionResult BlogSearch(string search_string, int Sayfa = 1)
{
var searchList = db.Blog.Include("Kategori").Where(
x => x.Icerik.Contains(search_string)).OrderByDescending(x => x.BlogId).ToPagedList(Sayfa, 5);
return View(searchList);
}

get html 5 date input field and pass to .net controller

On my razor page, I have a simple date picker that looks like this:
<input type="date" name="lessonsStart">
How would I go about getting the value of that and sending it to my controller?
Whenever I send data to my controller from a razor page, the format always looks something like this:
<a asp-action="LessonIndex" asp-route-id="#item.Id">#Html.DisplayFor(modelItem => item.Name)</a>
which sends an "item.Id" to my controller called LessonIndex().
So I'm not sure how I'd get the date value and send it.
The controller looks like this:
public IActionResult LessonIndex(datetime startDate) {
var response = getLessons(startDate);
return response.Results;
}
Is there a specific format I need to use?
Note that the date is not used in a model, it just needs to be sent to a controller.
Thanks!
Assuming this is related to mvc the controller would have a method associated with the post that you would perform to get the data from the form back to the controller. This uses javascript to post data to your LessonIndex() method.
<!--top of your page.-->
#inject Microsoft.AspNetCore.Antiforgery.IAntiforgery Xsrf
#functions{
public string GetAntiXsrfRequestToken()
{
return Xsrf.GetAndStoreTokens(Context).RequestToken;
}
}
<input type="date" id="lessonStart" name="lessonStart" />
<input type="Submit" id="PostButton" name="PostButton" Value="Go" />
#section Scripts{ // razor section at the bottom of mvc page 'cshtml'.
<script type="javascript">
$(function(){
$("#PostButton").click(function(){
var url = '#Url.Action("LessonIndex", "Lesson")'; //assuming controller is named Lesson
var date= new Date(this.value).ToDateString();
$.ajax({
url: url,
type: "POST",
data: "lessonStart=" + date,
headers:{
"RequestVerificationToken": '#GetAntiXsrfRequestToken()'
},
success: function(response){
console.log(response);
},
error: function(e){
console.log(e.error);
}
});
});
}
</script>
}
this also assumes that the method looks like this
public class LessonController : Controller{
[HttpPost]
[AutoValidateAntiforgeryToken]
public IActionResult LessonIndex(DateTime lessonStart){
var response = getLessons(lessonStart);
return View(response.results);
}
}
" Note that the date is not used in a model, it just needs to be sent to a controller. "
You could use the ajax to pass the date as QueryString to the method in the controller.
Here is the test example
<input type="date" name="lessonsStart" id="lessonsStart">
#section Scripts
{
<script type="text/javascript">
$("#lessonsStart").change(function () {
var inputDate = new Date(this.value).toDateString();
$.ajax({
type: "post",
url: "/ControllerName/lessonindex?startdate=" + inputDate,
success: function () { }
});
});
</script>
}
The method in controller
[HttpPost]
public IActionResult LessonIndex(DateTime startDate)
{
return Json(startDate);
}
<div class="demo-section k-content">
<h4>Remind me on</h4>
#(Html.Kendo().DateTimePicker()
.Name("datetimepicker")
.Value(DateTime.Now)
.HtmlAttributes(new { style = "width: 100%", title = "datetimepicker" })
.DateInput()
)
</div>

How to convert the returned XML to HTML?

I created a simple web service in ASP.net that does some operations:
[WebMethod]
public int Area(int l, int b)
{
return l * b;
}
[WebMethod]
public int Perimeter(int l, int b)
{
return 2 * (l +b);
}
and i called it in HTML file, like:
<html>
<head>
<title>WebService Call using HTTP POST</title>
<body>
<form action="http://localhost:56472/WebSite2/Service.asmx/Area" method="POST">
<input name="l">
<input name="b">
<input type="submit" value="Click for Area">
</form>
<form action="http://localhost:56472/WebSite2/Service.asmx/Perimeter" method="POST">
<input name="l">
<input name="b">
<input type="submit" value="Click for Perimeter">
</form>
</body>
</head>
</html>
put this when i click for the result it will be returned as XML:
<?xml version="1.0" encoding="UTF-8"?>
<int xmlns="http://tempuri.org/">30</int>
And what I want is i want the result in HTML not XML, how to do this?
Can someone help, please?
Thank You :)!
You'll need to call the service via ajax call and use the response to populate the required tag in the HTML.
Check the code below, it's simple jQuery AJAX call,
$.ajax({
url: "http://localhost:56472/WebSite2/Service.asmx/Area",
method:"post",
data: {
l: "custom value",
b: "custom value",
}
success: function (data) {
console.log(data.length);
var xmlDoc = $.parseXML(data);
var jXml = $(xmlDoc);
var value = jXml.find("int").text();
$("#result").text(value);
},
failure: function (err) {
console.log("could not call the service : " + err);
}
});
Couple of things to keep in mind
Form submission will take you to next page and destroy Javascript context, that's why we need AJAX call which will just bring us the result from teh service without navigating away from the page.
As server is returning data in XML you'll have to parse it either as XML document or as plain string to get the required values.
***Edited to add
Check out the complete example below.
<html>
<head>
<script src="https://code.jquery.com/jquery-2.1.4.min.js"></script>
<script>
<!-- create the function to call on click of a button -->
function getData() {
$.ajax({
url: "http://localhost:56472/WebSite2/Service.asmx/Area",
type: 'GET',
dataType: "xml",
data: {
l: "custom value",
b: "custom value"
},
success: function(data) {
console.log("success " + data);
console.log(data.getElementsByTagName("int"));
var xmlDoc = data;
if(typeof(data) === "string") {
xmlDoc = $.parseXML(data);
}
var value = xmlDoc.getElementsByTagName("int")[0].textContent;
$("#result").text(value);
},
error: function(err) {
console.log("error " + JSON.stringify(arguments));
}
});
}
</script>
</head>
<body>
<!-- see the onclick attribute, you have to call your Javascript function in it's value -->
<button onclick="getData();">click to get data</button>
<!-- tag where it result will be displayed -->
<h1 id="result">No result yet</h1>
</body>
</html>

MVC3 Partial View : Not able to see html in View Source for Partial View render using Json object

This is the first time I am working with ASP.NET MVC and I am stuck.
In my code I am doing an Ajax call by using JQuery/json, passing an array of selected options on button click to the controller side and performing some operations there.
Then I return a Partial View which is containing a table so I can see the contents of the Partial View (i.e., Grid) on the page.
Now I want go through the grid but when I try to inspect it I realize that there is no HTML code created in the browser's View Source.
Am I missing any basic thing over here? Can anyone help on this?
Controller - Main action method for View :
public ActionResult AssignCalculationToSC()
{
//Some Oprations performed
return View();
}
Action method called from Ajax to return Partial View :
public ActionResult AddSelectedList(string selectedList, string calculationPurpose)
{
List<AssignCalculationsSourceDataModel> lstAssignCalculationsSourceDataModel = new List<AssignCalculationsSourceDataModel>();
AssignCalculationsSourceDataModel assignCalculationsSourceDataModel = new AssignCalculationsSourceDataModel();
return PartialView("AssignCalculationToSC", lstAssignCalculationsSourceDataModel);
}
JQuery code for Ajax call :
$(function () {
$('#btnAdd').click(function () {
var selectedList = [];
$("#ddlSupplementalCalculationList option:selected").each(function (i, selected) {
var $this = $(this);
selectedList.push({ Id: $this.val(), Value: $this.text() });
});
getCalculationListGrid(selectedList, calculationPurpose);
});
function getCalculationListGrid(selectedList, calculationPurpose) {
$.ajax(
{
url: "AddSelectedList/SupplementalPricing",
type: "POST",
dataType: "html",
traditional: true,
data: { selectedList: JSON.stringify(selectedList), calculationPurpose: calculationPurpose },
success: function (response)
{
$("#dvGrid").html(response);
}
});
}
});
Main View :
#{
ViewBag.Title = "Assign Price Values";
}
#model IList<Bnym.Equinox.Accounting.Web.Portal.Models.Pricing.AssignCalculationsSourceDataModel>
#{Html.RenderPartial("PartialAssignCalculationGrid", Model);}
Partial View :
#model IList<Bnym.Equinox.Accounting.Web.Portal.Models.Pricing.AssignCalculationsSourceDataModel>
#if (Model != null)
{
<div id="dvGrid">
<table id="grid" style="table-layout: fixed;">
</table>
</div>
}
Q1) Now I want go through the grid but when I try to inspect it I realize that there is no HTML code created in the browser's View Source.
The HTML from your partial view will never appear in the page's source because it is not present in the initial HTTP GET. The View Source command in browsers displays the HTML received before any javascript is executed.
Download and install fiddler and inspect the Ajax call in order to see the HTML that is returned from your controller.
Q2 (implicit) Why is the partial view never displayed on screen?
Your main view needs a div#dvgrid and your partial view needs to hosts the grid's content, like this:
Main View :
#{
ViewBag.Title = "Assign Price Values";
}
#model IList<Bnym.Equinox.Accounting.Web.Portal.Models.Pricing.AssignCalculationsSourceDataModel>
<div id="dvGrid">
</div>
Partial View :
#model IList<Bnym.Equinox.Accounting.Web.Portal.Models.Pricing.AssignCalculationsSourceDataModel>
#if (Model != null)
{
<table id="grid" style="table-layout: fixed;">
#foreach(var item in Model){
<tr>
<td>
DATA <!-- render data here -->
</td>
<!-- ... -->
</tr>
}
</table>
}
Edit
You need to decorate your AddSelectedList action with an [HttpPost] attribute in your controller:
[HttpPost]
public ActionResult AddSelectedList(string selectedList, string calculationPurpose)
{
List<AssignCalculationsSourceDataModel> lstAssignCalculationsSourceDataModel = new List<AssignCalculationsSourceDataModel>();
AssignCalculationsSourceDataModel assignCalculationsSourceDataModel = new AssignCalculationsSourceDataModel();
return PartialView("AssignCalculationToSC", lstAssignCalculationsSourceDataModel);
}
And you need to fix your ajax call. Note the JSON.stringify() method has to wrap your whole javascript object.
$.ajax(
{
url: "#Url.Action("GetData")",
type: "POST",
dataType: "json",
traditional: true,
data: JSON.stringify({ selectedList: selectedList, calculationPurpose: calculationPurpose }),
success: function (response)
{
$("#dvGrid").html(response);
}
});

json data not rendered in backbone view

I have been trying to render the json data to the view by calling
the rest api and the code is as follows:
var Profile = Backbone.Model.extend({
dataType:'jsonp',
defaults: {
intuitId: null,
email: null,
type: null
},
});
var ProfileList = Backbone.Collection.extend({
model: Profile,
url: '/v1/entities/6414256167329108895'
});
var ProfileView = Backbone.View.extend({
el: "#profiles",
template: _.template($('#profileTemplate').html()),
render: function() {
_.each(this.model.models, function(profile) {
var profileTemplate = this.template(this.model.toJSON());
$(this.el).append(tprofileTemplate);
}, this);
return this;
}
});
var profiles = new ProfileList();
var profilesView = new ProfileView({model: profiles});
profiles.fetch();
profilesView.render();
and the html file is as follows:
<!DOCTYPE html>
<html>
<head>
<title>SPA Example</title>
<!--
<link rel="stylesheet" type="text/css" href="src/css/reset.css" />
<link rel="stylesheet" type="text/css" href="src/css/harmony_compiled.css" />
-->
</head>
<body class="harmony">
<header>
<div class="title">SPA Example</div>
</header>
<div id="profiles"></div>
<script id="profileTemplate" type="text/template">
<div class="profile">
<div class="info">
<div class="intuitId">
<%= intuitId %>
</div>
<div class="email">
<%= email %>
</div>
<div class="type">
<%= type %>
</div>
</div>
</div>
</script>
</body>
</html>
This gives me an error and the render function isn't invoking
properly and the render function is called even before the REST
API returns the JSON response.
Could anyone please help me to figure out where I went wrong. Any help is highly appreciated
Thank you
Firstly, you need to pass the model attributes to the template function explicitly. So change the appropriate code in the view to:
var ProfileView = Backbone.View.extend({
el: "#profiles",
//template: _.template($('#profileTemplate').html()), REMOVED
render: function() {
_.each(this.model.models, function(profile) {
var profileTemplate = _.template($('#profileTemplate').html(), {
intuitId: profile.get("intuitId"),
email: profile.get("email"),
type: profile.get("type")
});
$(this.el).append(tprofileTemplate);
}, this);
return this;
}
});
Secondly, your render method is not dependent on the fetch response from being returned from the server. It will get called immediately after the line above it executes and not wait for the fetch response. This behavior you are experiencing is by design. If you want to call render after you get the response back from the server you'll have to use events. You could replace profilesView.render(); with something like:
profilesView.listenTo(profiles, "sync", profilesView.render);
This means that the profilesView will listen for the profiles collection to complete its fetch and fire a sync event. When this occurs, the render function of the view will be called.