autocomplete in asp.net mvc (razor) - asp.net-mvc

I'm trying to implement the autocomplete function in my website, but won't work properly.
Here is the code of my view:
<script src="~/Scripts/jquery-ui-1.8.20.js" type="text/javascript"></script>
<script src="~/Scripts/jquery-ui-1.8.20.min.js" type="text/javascript"></script>
<script type="text/javascript">
$(function () {
$("#SearchString").autocomplete({
source: "/Test/AutocompleteSuggestions",
minLength: 1,
select: function (event, ui) {
if (ui.item) {
$("#SearchString").val(ui.item.value);
$("form").submit();
}
}
});
});
</script>
#using (Html.BeginForm())
{
<p>
Find by name: #Html.TextBox("SearchString")
<input type="submit" value="Search" /></p>
}
Here is code of my autoComplete controller action:
public JsonResult AutocompleteSuggestions(string searchstring)
{
var suggestions = from s in db.Students
select s.Name;
var namelist = suggestions.Where(n => n.ToLower().StartsWith(searchstring.ToLower()));
// return namelist.ToList();
return Json(namelist, JsonRequestBehavior.AllowGet);
}
Can anyone help me ?
Thanks in advance

you are trying to pass IQueryable. try replacing it with
return Json(namelist.ToList(), JsonRequestBehavior.AllowGet);
if that still doesnt work.
try replacing "searchString" to "term"
public JsonResult AutocompleteSuggestions(string term)
Ive read an article that you must use the "term" query string. but Im not pretty sure about it.

Related

GridMvc disappear after refresh by filter or sorting

I am using the GridMvc from this link:
https://gridmvc.codeplex.com
I don't have problem when I have a grid in a simple new page. but when my grid is under menu(menu seems is refreshing the page) when I use sort or filter on the grid, grid disappears.
This is my controller code:
public ActionResult Index()
{
DAL.DataManager dal = new DAL.DataManager();
List<data> data = new List<data>();
data = dal.get_AllDate();
return View(data);
}
and this is my view:
#using GridMvc.Html
#model IEnumerable<data>
#{
ViewBag.Title = "Index";
}
<script src="#Url.Content("~/Scripts/jquery.min.js")" type="text/javascript"> </script>
<link href="#Url.Content("~/Content/Gridmvc.css")" rel="stylesheet" type="text/css" />
<script src="#Url.Content("~/Scripts/gridmvc.min.js")" type="text/javascript"> </script>
#Html.Grid(Model).Columns(columns =>
{
columns.Add(model => model.dataUser).Titled("User").SetWidth(110);
columns.Add(model => model.Create_Date).Titled("Create Date").SetWidth(110).Filterable(true).Format("{0:dd/MM/yyyy}");
......
}).WithPaging(20).Sortable().Filterable().WithMultipleFilters()
I got this error too, as I noted it was performing GET and not POST, so as a workaround, I used the following at the end of the cshtml file:
#section Scripts {
<script type="text/javascript">
$(function(){
$(".grid-header-title").click(function (e) {
if ($(e.target).is("a")) {
// It was the anchor element that was clicked -- meaning, its sortable
e.preventDefault();
// '/Search' should be replaced with your form action
$(document.forms[0]).attr("action", '/Search' + $(e.target).attr("href"));
$(document.forms[0]).submit();
}
});
});
</script>
}

LINQ Query is not displaying mt data in my Google chart (Report)

I have a LINQ query which gets the Type and count of types, and I have it in my controller. In my view I am using a Pie Chart from Google Charts and I am trying to display the data acquired by the LINQ statement. However, when I run the program the Pie Chart doesn't display. No errors appear though. So I am struggling to see whether my problem is my View or the Controller
Controller:
public ActionResult Report_5()
{
return View();
}
public ActionResult GetChart5()
{
var result = from x in db.Submission
group x by x.Type into grp
select new
{
Type = grp.Key,
Count = grp.Count()
};
return Json(result, JsonRequestBehavior.AllowGet);
}
Report_5 View:
<h2 style="text-align:center">Type Count</h2>
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.11.0/jquery.min.js"></script>
<script src="//netdna.bootstrapcdn.com/bootstrap/3.1.1/js/bootstrap.min.js"></script>
<script src="//ajax.aspnetcdn.com/ajax/jquery.validate/1.11.1/jquery.validate.min.js"></script>
<script src="//ajax.aspnetcdn.com/ajax/mvc/4.0/jquery.validate.unobtrusive.min.js"></script>
<script type="text/javascript" src="https://www.google.com/jsapi"></script>
<script type="text/javascript">
google.load("visualization", "1", { packages: ["corechart"] });
google.setOnLoadCallback(drawChart);
function drawTable() {
var data = new google.visualization.DataTable();
data.addColumn('string', 'Type');
data.addColumn('string', 'Count');
$.getJSON("#Url.Action("GetChart5")", null, function (chartData) {
$.each(chartData, function (i, item) {
data.addRow([item.Type, item.Count]);
});
var chart = new google.visualization.PieChart(document.getElementById('donutchart'));
chart.draw(data, options);
});
}
</script>
<div id="donutchart" style="width: 900px; height: 500px;"></div>
Please let me know if I need to provide more information.
I made the following:
1. created view in folder Models.
public class ModelSubmission
{
public string Type { get; set; }
public int TotalSubmissions { get; set; }
}
In home controller created the following:
public ActionResult Report_5()
{
return View();
}
public ActionResult GetChart5()
{
List<ModelSubmission> result = new List<ModelSubmission>();
result.Add(new ModelSubmission() { Type="Book", TotalSubmissions = 3 });
result.Add(new ModelSubmission() { Type = "Book chapter", TotalSubmissions = 7 });
result.Add(new ModelSubmission() { Type = "Journal Article", TotalSubmissions = 3 });
return Json(result, JsonRequestBehavior.AllowGet);
}
And then copy/pasted your view. Then executed for debugging, and as you mentioned seen nothing special. After clicking F12 in chrome I noticed following error message:
Uncaught ReferenceError: drawChart is not defined.
It lead me to conclusion, that in your code instead of
google.setOnLoadCallback(drawChart);
you should write
google.setOnLoadCallback(drawTable);
After some debugging I noticed other errors in your code. Try to find them while watching the following view:
<h2 style="text-align:center">Type Count</h2>
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.11.0/jquery.min.js"> </script>
<script src="//netdna.bootstrapcdn.com/bootstrap/3.1.1/js/bootstrap.min.js"></script>
<script src="//ajax.aspnetcdn.com/ajax/jquery.validate/1.11.1/jquery.validate.min.js"> </script>
<script src="//ajax.aspnetcdn.com/ajax/mvc/4.0/jquery.validate.unobtrusive.min.js"> </script>
<script type="text/javascript" src="https://www.google.com/jsapi"></script>
<script type="text/javascript">
google.load("visualization", "1", { packages: ["corechart"] });
google.setOnLoadCallback(drawTable);
function drawTable() {
var data = new google.visualization.DataTable();
data.addColumn('string', 'Type');
data.addColumn('number', 'Count');
$.getJSON("#Url.Action("GetChart5")", null, function (chartData) {
$.each(chartData, function (i, item) {
data.addRow([item.Type, item.TotalSubmissions]);
});
var chart = new google.visualization.PieChart(document.getElementById('donutchart'));
var options = {
'title': 'Forgotten input',
'width': 400,
'height': 300
};
chart.draw(data, options);
});
}
You should be more careful when copy/paste code from other pages

How to use jQuery UI in ASP.NET MVC 5

I'm trying to create an autocomplete text box using Jquery UI.
I can see that GetActiveItems works fine and i got a json result , but I can't see the autocomplete on the screen. I think that the problam is in the 'OnActionExecuted' when the ActionResult is being execute.
Please help me :)
thanks,
Siri
View:
<input type="text" id="mpvalue" name="mpvalue" />
<script type="text/javascript">
$(document).ready(function () {
$('#mpvalue').autocomplete({
source: '#Url.Action("GetActiveItems")'
});
})
</script>
Controller:
public ActionResult GetActiveItems(string term)
{
var result = from e in db.Items
where (e.IsBlock != true) && (e.Description.ToLower().Contains(term))
select e.Description;
return Json(result, JsonRequestBehavior.AllowGet);
}

Kendo MVC multiple uploaders

I'm using the kendo controls with MVC. I have a basic uploader working, but I need to create them dynamically and handle that code on the back end. Here's my simple example that's working
<input name="attachments" type="file" id="attachments" />
<script type="text/javascript">
$(document).ready(function () {
$("#attachments").kendoUpload({
async: {
saveUrl: '#Url.Action("Save", "AppConfig")',
autoUpload: true
}
});
});
</script>
[HttpPost]
public ActionResult Save(IEnumerable<HttpPostedFileBase> attachments)
{
if (SaveUploadedFile(attachments, "Background"))
{
return Content("");
}
else
{
return Content("error");
}
}
However, what I need to do is create the ids dynamically and handle it on the backend. So this is how I'm making the file uploaders
#foreach (var item in Model) {
string fid = String.Format("{0}{1}", #item.fieldType, #item.appConfigId.ToString());
<input name="#fid" id="#fid" type="file" />
<script type="text/javascript">
$(document).ready(function () {
$("##fid").kendoUpload({
async: {
saveUrl: '#Url.Action("Save", "AppConfig")',
autoUpload: true
}
});
});
</script>
}
Now I get that the HttpPostedFileBase argument has to match your id of your html element, but I have no idea how to modify the code behind, so that I can take in multiple uploaders. Any ideas?
Why don't you just use the multiple functionality of the Uploader? It is enabled by default.

MVC autocomplete not working

I know there are lot of posts out there but simply I can not figure out what I am doing wrong in autocomplete.
I have a ProductController like
public JsonResult AutocompleteMethod(string searchstring) //searchString null here
{
Product ob=new Product();
List<Product> newLst = ob.GetProducts();
var suggestions = from s in newLst select s.productName ;
var namelist = suggestions.Where(n=>n.StartsWith(searchstring));
return Json(namelist, JsonRequestBehavior.AllowGet);
}
In view I have:
<p>
Find by name:<%: Html.TextBox("Txt") %>
</p>
<link rel="stylesheet" href="http://code.jquery.com/ui/1.10.0/themes/base/jquery-ui.css" />
<script src="http://code.jquery.com/jquery-1.8.3.js" type="text/javascript"></script>
<script src="http://code.jquery.com/ui/1.10.0/jquery-ui.js" type="text/javascript"></script>
<script type="text/jscript">
$(function () {
debugger;
$('#Txt').autocomplete({ source: '/Product/AutocompleteMethod' });
});
</script>
But always SearchString is NULL in controller function.
Can you figure out what is the mistake?
AFAIK the parameter is called term, not searchstring, so:
public ActionResult AutocompleteMethod(string term)
{
List<Product> newLst = new Product().GetProducts();
var namelist =
from p in newLst
where p.StartsWith(term)
select new
{
value = p.Id, // you might need to adjust the Id property name here to match your model
label = p.productName
};
return Json(namelist, JsonRequestBehavior.AllowGet);
}
Also I very much doubt that productName is a property that the autocomplete plugin will ever recognize. You could try using value and label as shown in the projection I performed in my example.

Resources