Autocomplete not working in asp.net mvc - asp.net-mvc

I am trying to create a textbox that autocomplete when a user start do search for some name, but it's not working.
Here is my view:
<link href="http://ajax.googleapis.com/ajax/libs/jqueryui/1.8/themes/cupertino/jquery-ui.css" type="text/css" rel="Stylesheet" />
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.4/jquery.min.js" type="text/javascript"></script>
<script src="http://ajax.googleapis.com/ajax/libs/jqueryui/1.8/jquery-ui.min.js" type="text/javascript"></script>
<script type="text/javascript">
$(document).ready(function () {
$("#txtSearch").autocomplete({
source: '#Url.Action("pesquisarUsuario")',
minLength: 0
});
});
</script>
<h2>Index</h2>
#using (#Html.BeginForm())
{
#Html.TextBox("pesquisa", null, new { id = "txtPesq" })
<input type="submit" value="Pesquisar" />
}
And here is my controller:
public JsonResult pesquisarUsuario(string term)
{
List<string> usuario;
usuario = db.usuario.Where(u => u.nomecompleto.StartsWith(term))
.Select(u => u.nomecompleto).ToList();
return Json(usuario, JsonRequestBehavior.AllowGet);
}
Am I missing something? because my textbox does not show any users when I start do write.

First try if usuario returns anything. :-)
Try in your browser: http://localhost:port/yourcontroller/pesquisarUsuario?term=t
It should return all records starting with 't'.
If it does not return anything, here is your problem.
If it does, try to set the full url:
$(document).ready(function () {
$("#txtSearch").autocomplete({
source: 'http://yourserver/yourcontroller/pesquisarUsuario',
minLength: 0
});
});
EDIT:
I have created this tutorial with a fully working example: http://r2d2.cc/2014/09/11/autocomplete-jquery-ui-with-asp-net-mvc-simple-example/

Related

showing a view as popup in mvc4 pattern

I've a view rendered with Razor engine and I need to open at a button click a popup to insert a new user (i've already got my view/controller for the InsertUser)
I wish to know what the correct workflow to perform this, if I open it with jQuery how do I tell after the insert to close the view? my controller doesn't know it's on a popup and I've not seen any CloseResult as ActionResult... I'm using also KendoUI, I've seen it has the Window control....this as well won't help me on this.....what's best to use for opening a popup?
Thanks
Try reading this article on progressive enhancement, while you might not want to do it progressivly the article contains all the little recipes you will need to do it.
Your get action would be like this:
[HttpGet]
public ActionResult ContactUs()
{
return PartialView("_ContactUs");
}
Your post like this:
[HttpPost]
public ActionResult ContactUs(ContactUsInput input)
{
if (!ModelState.IsValid)
{
return PartialView("_ContactUs", input);
}
return PartialView("_ThanksForFeedback", input);
}
The front end something like this:
<script src="#Url.Content("~/Scripts/jquery-1.4.4.min.js")" type="text/javascript"></script>
<script src="#Url.Content("~/Scripts/jquery-ui.js")" type="text/javascript"></script>
<script src="#Url.Content("~/Scripts/jquery.validate.min.js")" type="text/javascript"></script>
<script src="#Url.Content("~/Scripts/jquery.validate.unobtrusive.min.js")" type="text/javascript"></script>
<script src="#Url.Content("~/Scripts/jquery.unobtrusive-ajax.js")" type="text/javascript"></script>
<script type="text/javascript">
$.ajaxSetup({ cache: false });
$(document).ready(function () {
$(".openDialog").live("click", function (e) {
e.preventDefault();
$("<div></div>")
.addClass("dialog")
.attr("id", $(this).attr("data-dialog-id"))
.appendTo("body")
.dialog({
title: $(this).attr("data-dialog-title"),
close: function () { $(this).remove() },
modal: true
})
.load(this.href);
});
$(".close").live("click", function (e) {
e.preventDefault();
$(this).closest(".dialog").dialog("close");
});
});
</script>
<a class="openDialog" data-dialog-id="emailDialog"
data-dialog-title="Contact Us" href="/Home/ContactUs">Contact Us</a>

jQuery never called

I'm trying to implement the solution provided in this question here:
How to pass Model Value through ActionLink
So in my view I have an action link
#Html.ActionLink("Look up registration", "RegLookup", "Vehicle", new {#id="check"},null)
And in a Javascript file I have :
$(function ()
{
$("#check").click(function (e) {
e.preventDefault();
}
I've cut the function down to just preventing the default action of the action link.
In the view I've also referenced the java script files
<script src="~/Scripts/jquery-1.6.2.min.js" type="text/javascript"></script>
<script src="~/Scripts/jquery.unobtrusive-ajax.js" type="text/javascript"></script>
<script src="~/Scripts/GetRegistrationPlate.js" type="text/javascript"></script>
However when I click on the action link the default method continues to fire.
What might I have missed?
For one there are many syntax errors. Try this
$(function () {
$("#check").click(function (e) {
e.preventDefault();
return false;
});
});
Edit: Also, change the ActionLink to
#Html.ActionLink("Look up registration", "RegLookup", "Vehicle", new { #id = "check" }, new { #id = "check" })
The first id is for the route, the second id is for the html element.

jqGrid: No such method: restoreRow

I am having an issue working with jaGrid and ASP.NET MVC 2. Everything is working, but when I select a row I get this error on FireBug: uncaught exception: jqGrid - No such method: restoreRow.
Debugin Js I realize that error happend here:
onSelectRow: function(id) {
if (id && id !== lastsel) {
jQuery('#list').jqGrid('restoreRow', lastsel);
jQuery('#list').jqGrid('editRow', id, true);
lastsel = id;
}
I think, the problem is the jqGrid libraries include (or the include order). This is my Index.aspx page.
<%--CSS Files--%>
<link href="/Content/jquery-ui-1.8.7.css" rel="stylesheet" type="text/css" />
<link href="/Content/ui.jqgrid.css" rel="stylesheet" type="text/css" />
<link href="/Content/ui.multiselect.css" rel="stylesheet" type="text/css" />
<%--jQuery Library--%>
<script type="text/javascript" src="../../Scripts/jquery-1.4.4.min.js"></script>
<%--Must load language tag BEFORE script tag--%>
<script type="text/javascript" src="../../Scripts/grid.locale-es.js"></script>
<script type="text/javascript" src="../../Scripts/jquery.jqGrid.min.js"></script>
<script type="text/javascript" src="../../Scripts/grid.jqueryui.js"></script>
<script type="text/javascript" src="../../Scripts/grid.base.js"></script>
<script type="text/javascript" src="../../Scripts/grid.common.js"></script>
<script type="text/javascript" src="../../Scripts/grid.formedit.js"></script>
<script type="text/javascript" src="../../Scripts/jquery.fmatter.js"></script>
<script type="text/javascript" src="../../Scripts/grid.custom.js"></script>
<script type="text/javascript" src="../../Scripts/jqDnR.js"></script>
<script type="text/javascript" src="../../Scripts/jqModal.js"></script>
<script type="text/javascript" src="../../Scripts/grid.import.js"></script>
</asp:Content>
<asp:Content ID="Content2" ContentPlaceHolderID="MainContent" runat="server">
<table id="tableAccidentes" border=0>
<tr>
<td><img alt="" src="../../images/icono_victima.png" /></td>
<td><h2>Accidentes Registrados</h2></td>
</tr>
</table>
<script type="text/javascript">
var lastsel;
var Plantas = ['Pablo Podesta', 'Pilar', 'Tigre', 'Otra'];
jQuery(document).ready(function() {
jQuery("#list").jqGrid({
url: '/Accidentes/ListarAccidentes',
datatype: "json",
colNames: ['Fecha', 'Detalle', 'Accidentado', 'Planta'],
colModel: [
{ name:'Fecha', index:'Fecha', width:150, align:'left',
editable:true },
{ name:'Detalle', index:'Detalle', width:150, align:'left',
editable:true },
{ name:'Accidentado', index:'Accidentado', width:200,
align:'left', editable:true },
{ name:'planta', index:'planta', width:150, align:'left',
editable:true, edittype:"select",
editoptions: { value:Plantas} }
],
onSelectRow: function(id) {
if (id && id !== lastsel) {
jQuery('#list').jqGrid('restoreRow', lastsel);
jQuery('#list').jqGrid('editRow', id, true);
lastsel = id;
}
},
editurl: "/Accidentes/GridSave",
edit: {
addCaption: "Agregar Accidente",
editCaption: "Editar Accidente",
bSubmit: "Guardar",
bCancel: "Cancelar",
bClose: "Cerrar",
saveData: "Se modifico el registro! ¿guardar los cambios?",
bYes: "Si",
bNo: "No",
bExit: "Cancelar"
},
pager: jQuery('#pager'),
rowNum: 10,
rowList: [5, 10, 20, 50],
sortname: 'Id',
sortorder: "desc",
viewrecords: true,
imgpath: '/scripts/themes/coffee/images',
caption: 'Accidente'
}).navGrid('#pager', { edit: true, add: true, search: false, del: false },
{ closeAfterAdd: true, closeAfterEdit: true });
// add custom button to export the data to excel
jQuery("#list").jqGrid('navButtonAdd','#pager',{
caption:"",
onClickButton : function () {
jQuery("#list").jqGrid('excelExport',
{ url: '/Accidentes/ExportarAccidentes' });
}
});
});
</script>
<%-- HTML Required--%>
<table id="list" class="scroll" cellpadding="0" cellspacing="0"></table>
<div id="pager" class="scroll" style="text-align:center;"></div>
Please, can someone help me?
The restoreRow and editRow methods, which you use, are defined in the grid.inlinedit.js file and are the part of the inline editing module (see more in the jqGrid documentation). Moreover you should remove the file jquery.jqGrid.min.js to avoid having definitions of the same functions twice. Because the method restoreRow was not defined in the jquery.jqGrid.min.js which you use you use probably wrong downloaded jqGrid version. You should download the jqGrid one more time and be sure that you check "Inline Editing" module. If you open jquery.jqGrid.min.js file in the text editor you will see in the comment at the begining of the file all modules which was the part of the download.
Some additional small remarks: in the documentation is described which parameters of the colModel are default. For example, width:150 and align:'left' have defaout values, so you can remove there from the column definition.
The value property for "select" type of the editoptions which you use is wrong. The Plantas should be defined as
var Plantas = { 'Pablo Podesta':'Pablo Podesta', Pilar:'Pilar',
Tigre:'Tigre', Otra:'Otra'};
or as
var Plantas = 'Pablo Podesta:Pablo Podesta;Pilar:Pilar;Tigre:Tigre;Otra:Otra';
See the documentation for details.
The parameter imgpath is deprecated and should be removed. Class "scroll" is also deprecated and the HTML fragment for the jqGrid can be reduced to
<table id="list"></table>
<div id="pager"></div>
See an example here.
The parameter edit is not exist in the jqGrid it is the parameter of editGridRow from the form editing. You can define it as the part of navGrid parameters prmEdit and prmAdd. Currently you use only prmEdit. Probably the usage of grid.locale-XX.js from the i18n directory will make the usage of edit parameter unneeded.

ASP.NET MVC | Problem about showing modal dialog using jQuery dialog widget

I am very fresh to asp.net mvc and jQuery. After one day trying, I still don't know how to pop up a jQuery dialog using data from a action(return JsonResult) while user click a link.
Any suggest or guideline is appreciate.
Thanks!
Thx for Stuntz & RhinoDevX64 's reply, finally I work it out.
jQuery Code:
<script type="text/javascript">
$(function() {
$('.newsitem').click(function() {
var $thisLink = $(this);
$('#dialog').empty();
$.getJSON($thisLink.attr("href"), function(data) {
$('#dialog').html(data.content);
$("#dialog").dialog({
autoOpen: false,
title: data.title,
bgiframe: true,
modal: true,
height: 450,
width: 540,
buttons: {
'关闭': function() {
$(this).dialog('close');
}
}
});
$('#dialog').dialog('open');
});
return false;
});
});
</script>
ActionLink
<%= Html.ActionLink(item.Title, "GetByJs", "Article", new { id = item.ID }, new { #class = "newsitem" })%>
Action Code
public ActionResult GetByJs(Guid id) {
var item = Article.SingleOrDefault(a => a.ID == id && a.AtFront == true);
var jsonData = new {
title = item.Title, content = item.BodyContent
};
return new JsonResult {
Data = jsonData
};
}
var ph = $("#idOfPlaceHolderInPage");
ph.load(/Controller/SomeActionWhichReturnsPartialView, function() {
// this callback will be called after your partial view loaded into placeholder
ph.dialog({
// pass options here to customize dialog
});
});
1st use jQuery UI follow their documentation for including the css and js files.
<script src="../../Scripts/jquery-1.3.2.js" type="text/javascript" ></script>
<script src="../../Scripts/jquery-ui-1.7.1.custom.min.js" type="text/javascript"></script>
<link href="../../Content/jquery-ui-1.7.1.custom.css" rel="stylesheet" type="text/css" />
<script type="text/javascript">
$(document).ready(function(){
$("#idOfModalPlaceholder").dialog({autoOpen: false, title:"MODAL TITLE"});
});
function OpenModalGetContent(){
$("#idOfModalPlaceHolder").load("/Controller/View");
$("#idOfModalPlaceHolder").dialog('open');
}
</script>
CLICK HERE FOR MODAL
2nd You should really just use a regular ActionResult and a Partial View (*.ascx), if you are just grabbing some content;
if you are calling data I presume you may be loading into an autocomplete which would be completely different than this scenario.

How do I make Ajax.ActionLink update an element instead of navigating the whole page?

I am trying to update a <div> in my view when the user clicks on an Ajax.ActionLink. However, it always navigates the entire page rather than inserting the server's response into the element I specify.
I feel like I'm doing everything in this example, but even after creating the simplest test case I still can't create the behavior I want.
In the test case that follows, I load /Company/test and after clicking on "Go!", I expected the <div> to be replaced with "All done", but instead the whole page navigates to /Company/test_ajax.
I'm sure I'm missing something here. Thanks in advance.
CompanyController
public ActionResult test()
{
return View();
}
public ActionResult test_ajax()
{
return Content("All done");
}
test.aspx
<%# Page Title="" Language="C#" Inherits="System.Web.Mvc.ViewPage" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<title>test</title>
<script src="../../Scripts/jquery-1.3.2.min.js" type="text/javascript"></script>
<script src="../../Scripts/MicrosoftAjax.js" type="text/javascript"></script>
<script src="../../Scripts/MicrosoftMvcAjax.js" type="text/javascript"></script>
</head>
<body>
<h2>test</h2>
<%= Ajax.ActionLink("Go!", "test_ajax",
new AjaxOptions {
UpdateTargetId="viewport"
}) %>
<div id="viewport">Replace me!</div>
</body></html>
If You are using MVC 3 you will have to include "jquery.unobtrusive-ajax.js" as a reference. It should already be present in your Scripts folder. \m/
I have found that adding jquery.unobtrusive-ajax.js to my layout.cshtml page avoids all sorts of stupid "why does this not work?" moments when working with ajax objects/methods.
Your example works as expected on my computer. Check if files MicrosoftAjax.js and MicrosoftMvcAjax.js are really present in ../../Scripts folder.
I had to modify the AjaxOptions in my ActionLink call to get it working:
<%= Ajax.ActionLink("Update", "UpdateContent", new AjaxOptions() { HttpMethod = "Post", UpdateTargetId = "target", InsertionMode = InsertionMode.Replace })%>
Had problem with this too. I'm using VS2013 and jquery-1.10.2.min.js. Had to use a combination of 4 js files to get it to work. Hope this sample code helps someone.
Test.cshtml:
#{
Layout = null;
}
<!DOCTYPE html>
<html>
<head>
<meta name="viewport" content="width=device-width" />
<title>test</title>
<script src="#Url.Content("~/Scripts/jquery-1.10.2.min.js")" type="text/javascript"></script>
<script src="http://code.jquery.com/jquery-migrate-1.2.1.js"></script>
<script src="#Url.Content("~/Scripts/jquery.unobtrusive-ajax.js")" type="text/javascript"></script>
<script src="#Url.Content("~/Scripts/jquery.history.js")" type="text/javascript"></script>
<script type="text/javascript">
$(function () {
$.history.init(function (hash) {
if (hash.length > 0) {
$("#" + hash).click();
}
},
{ unescape: ",/" });
});
function AddHashTag(hashTag) {
window.location.hash = hashTag;
}
</script>
</head>
<body>
#Ajax.ActionLink("Render Circle", "GetCircle", null,
new AjaxOptions { HttpMethod = "Get", UpdateTargetId = "divContent", OnSuccess = "AddHashTag('circle')" },
new { #id = "circle" })
#Ajax.ActionLink("Render Diamond", "GetDiamond", null,
new AjaxOptions { HttpMethod = "Get", UpdateTargetId = "divContent", OnSuccess = "AddHashTag('diamond')" },
new { #id = "diamond" })
#Ajax.ActionLink("Render Star", "GetStar", null,
new AjaxOptions { HttpMethod = "Get", UpdateTargetId = "divContent", OnSuccess = "AddHashTag('star')" },
new { #id = "star" })
<div id="divContent" style="width: 300px; height: 300px; text-align: center; vertical-align: middle;
margin: 50px 50px;">
</div>
</body>
</html>
star.cshtml:
star<div class="star"></div>
diamond.cshtml:
diamond<div class="diamond"></div>
circle.cshtml:
circle<div class="circle"></div>
Home Controller:
public ActionResult Test()
{
return View();
}
[HttpGet]
public ActionResult GetCircle()
{
return PartialView("Circle");
}
[HttpGet]
public ActionResult GetDiamond()
{
return PartialView("Diamond");
}
[HttpGet]
public ActionResult GetStar()
{
return PartialView("Star");
}

Resources