ASP.NET MVC 4 autocomplete not working - asp.net-mvc

Hello I have a simple MVC autocomplete, the code I tested and it works when I create an "empty" mvc project, but when I do the exact code in intenet application it does not work, It never gets to autocomplete method. any ideas? so wired. Thank you
Home controller
static List<Students> _students = new List<Students>() {
new Students{id=1,Name="Bob", Grade="B"},
new Students{id=2,Name="Billy", Grade="A"},
new Students{id=3,Name="Mike", Grade="B"}
};
public ActionResult AutoMethod(string term)
{
//....
}
public ActionResult Index()
{
return View(_students);
}
index view
#model IEnumerable<MvcApplication1.Models.Students>
<script src="~/Scripts/jquery-1.10.2.js"></script>
<script src="~/Scripts/jquery-ui-1.10.4.custom.min.js"></script>
<link href="~/Content/jquery-ui-1.10.4.custom.min.css" rel="stylesheet" />
<script type="text/javascript">
$(function () {
$("#searchText").autocomplete({
source: '#Url.Action("AutoMethod")'
});
});
#using (Html.BeginForm()){
#Html.TextBox("searchText");
<input type="submit" value="submit" />
}
<table>
<tr>
<th>
#Html.DisplayNameFor(model => model.Name)
</th>
<th>
#Html.DisplayNameFor(model => model.Grade)
</th>
</tr>
#foreach (var item in Model)
{
<tr>
<td>
#Html.DisplayFor(modelItem => item.Name)
</td>
<td>
#Html.DisplayFor(modelItem => item.Grade)
</td>
</tr>
}

Please, take a look at the resulting HTML code in your browser, probably you are referencing JavaScript files more than once. It is not advised to reference commonly used JavaScript files from views; use your _SiteLayour.cshtml or MVC's "Bundling and minification" feature instead.

Add these to top of your autocomplete code:
<link rel="stylesheet" href="http://ajax.googleapis.com/ajax/libs/jqueryui/1.10.3/themes/excite-bike/jquery-ui.css" type="text/css" />
<script type="text/javascript" src="http://code.jquery.com/jquery-latest.js"></script>
<script src='http://code.jquery.com/ui/1.10.3/jquery-ui.js'></script>
And add jQuery.noConflict(); to your function:
$(function () {
jQuery.noConflict();
$("#searchText").autocomplete({
source: '#Url.Action("AutoMethod")'
});

Related

Asp.net Mvc Ajax Record Couldn't find

i am creating the Asp.net MVC Project in Bank Balance Checking.if i enter the correct account no relevant balance want to display but not not displayed while i am running the programming i got the error was Additional information: The underlying provider failed on Open.
what i tried so far i attached below.
Index.cshtml
#{
ViewBag.Title = "Index";
}
<div class="row">
<div class="col-sm-8">
#using (Html.BeginForm("Index", "home", FormMethod.Post, new { id = "popupForm" }))
{
<table class="table table-bordered">
<caption> Add Products </caption>
<tr>
<th>Account No</th>
<th>Account Holder Name</th>
<th>Balance</th>
</tr>
<tr align="center">
<td>
<input type="text" class="form-control" placeholder="Account No" id="accno" name="accno" size="50px">
</td>
<td>
<input type="text" class="form-control" id="accname" size="25px" name="accname"
placeholder="price" disabled>
</td>
<td>
<input type="number" class="form-control" id="balance" name="balance"
placeholder="qty" size="25px" required>
</td>
</tr>
</table>
}
</div>
</div>
<hr />
#Scripts.Render("~/bundles/jquery")
#section scripts{
<script src="~/Scripts/jquery-3.4.1.js"></script>
<script src="~/Scripts/jquery-3.4.1.min.js"></script>
<script src="~/Scripts/jquery.validate.js"></script>
<script src="//cdn.datatables.net/1.10.19/js/jquery.dataTables.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery-confirm/3.3.2/jquery-confirm.min.js"></script>
<script>
getProductcode();
function getProductcode()
{
$("#accno").empty();
$("#accno").keyup(function (e) {
var q = $("#accno").val();
if ($('#accno').val().length === 0) {
$.alert({
title: 'Error!',
content: "Please Enter the Barcode",
type: 'red',
autoClose: 'ok|2000'
});
return false;
}
$.ajax({
type: "POST",
url: '/home/Getid?id=' + $("#accno").val(),
dataType: "JSON",
success: function (data)
{
console.log(data);
$('#accname').val(data.accname);
$('#balance').val(data.balance);
},
error: function (xhr, status, error)
{
// alert("The barcode entered is not correct");
}
});
return true;
});
}
</script>
}
#section styles{
<link href="~/Content/bootstrap.css" rel="stylesheet" />
<link href="~/Content/bootstrap.min.css" rel="stylesheet" />
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/jquery-confirm/3.3.2/jquery-confirm.min.css">
<link rel="stylesheet" href="//cdn.datatables.net/1.10.19/css/jquery.dataTables.min.css">
}
HomeController
//you don't need this here except you want to use Dependency injection
bankEntities dc = new bankEntities();
public ActionResult Index()
{
return View();
}
public string accno { get; set; }
[HttpPost]
public JsonResult Getid(String Id)
{
var std = dc.accounts.Where(a => a.accno == Id).FirstOrDefault();
return Json(std, JsonRequestBehavior.AllowGet);
}
}

TBody not working on table with Jquery DataTable

I am using JQuery Data Table in my project.
I have ActionResult and getting data. I want to display data in table but if I use tbody, datatable is not styling look like normal table.
I tried without data and wrote custom tbody and tr tags. My probiem is continue. Where is my wrong ?
ActionResult
public ActionResult YayinEvleri()
{
dbContext = new DatabaseContext();
var yayinEvleri = dbContext.YayinEvi.ToList();
return View(yayinEvleri);
}
View
#model List<KitapFuari.Models.Yayinevi>
<link rel="stylesheet" type="text/css" href="https://cdn.datatables.net/1.10.19/css/jquery.dataTables.css">
<script type="text/javascript" charset="utf8" src="https://cdn.datatables.net/1.10.19/js/jquery.dataTables.js"></script>
<script src="https://cdn.datatables.net/1.10.19/js/dataTables.bootstrap4.min.js "></script>
<script>
$(document).ready( function () {
$('#yayinEvleri').DataTable();
});
</script>
<table id="yayinEvleri" class="table table-striped table-bordered" style="width:100%" cellspacing="0">
<thead>
<tr>
<th>Yayın Evi</th>
<th>Yazar</th>
</tr>
</thead>
<tbody>
#foreach (var item in Model)
{
<tr>
<td>#item.Ad</td>
</tr>
}
</tbody>
</table>
Add this script.
$(document).ready( function () {
$('#yayinEvleri').DataTable();
});

How to show partial view with parameter on click

I have a database with people and phones and i created a partial view that shows persons phones. I want this patial view to be loaded on click at some button like ShowPhones or something like that.
This is how i call view
#Html.Partial("ShowPersonsPhones", item.phones)
This is my partial view
#model IEnumerable<Project.Models.Phone>
<h2>Parial View</h2>
<table class="table">
<tr>
<th>
#Html.DisplayNameFor(model => model.Numer)
</th>
<th>
#Html.DisplayNameFor(model => model.Model)
</th>
</tr>
#foreach (var phone in Model)
{
<tr>
<td>
#Html.DisplayFor(item => phone.Numer)
</td>
<td>
#Html.DisplayFor(item => phone.Model)
</td>
</tr>
}
</table>
EDIT:
i tried to do some javascript in view but it just doesnt work
<style>
.shown{
display : inline;
}
.hidden{
display : none;
}
</style>
#Scripts.Render("~/bundles/jquery")
<script type="text/javascript">
function show_partial(i) {
alert("show partial " + i);
var divsname = '#partial' + i;
div = $(divsname);
if (div.hasClass('hidden'))
{
div.removeClass("shown");
div.addClass("hidden");
}
else
{
div.removeClass('hidden');
div.addClass("shown");
}
}
</script>
When i put alert in the function it shows but doesnt change classes for some reason.
In button click event, you can load the partial view.
ViewPage
<input type="button" id="btn" value="ClickMe" onclick="loadPartialView()" />
<div id="partialDiv"></div>
<script type="text/javascript">
function loadPartialView() {
$("#partialDiv").load('#Url.Action("IndexView","Home")');
}
</script>
In Controller, you can return the partial view with the parameter.
public ActionResult IndexView()
{
return PartialView("_PartialView", db.Phones.ToList());
}

Display partial view in a view using mvc 4

I want to display a partial view inside a main view upon clicking view link, within the same page. Help me please, I am newbie in MVC. Is there any other way to do it other than using the Ajax.ActionLink()?
This is my Add Detail controller.
public ActionResult DisplayDetails()
{
SqlConnection connect = new SqlConnection(ConfigurationManager.ConnectionStrings["connect"].ToString());
connect.Open();
DataSet ds = ExecuteQuery("select EmployeeID, EmployeeName, EmailID from EmployeeDetails");
IList<AddDetails> lst = new List<AddDetails>();
AddDetails ad;
foreach (DataRow dr in ds.Tables[0].Rows)
{
ad = new AddDetails();
ad.EmployeeId = Convert.ToInt32(dr["EmployeeID"]);
ad.EmployeeName = dr["EmployeeName"].ToString();
ad.EmailId = dr["EmailID"].ToString();
lst.Add(ad);
}
connect.Close();
return PartialView("DisplayDetails", lst);
}
Here is the main view
AddDetail view(main view).
#model mvcEmployeeTask.Models.AddDetails
<link href="#Url.Content("~/Content/Site.css")" rel="stylesheet" type="text/css" />
#using (Html.BeginForm("AddDetail", "AddDetails", FormMethod.Post))
{
<table>
#* <tr>
<td>
#(Html.Label("Employee ID : "))
</td>
<td>
#Html.TextBoxFor(model => model.EmployeeId)
#Html.HiddenFor(model => model.EmployeeId)
</td>
</tr>*#
#Html.HiddenFor(model => model.EmployeeId)
<tr>
<td>
#(Html.Label("Employee Name : "))
</td>
<td>
#(Html.TextBoxFor(model => model.EmployeeName))
</td>
</tr>
<tr>
<td>
#(Html.Label("Email ID : "))
</td>
<td>
#(Html.TextBoxFor(model => model.EmailId))
</td>
</tr>
<tr>
<td>
<input type="submit" value="submit" name="Add" />
</td>
<td>
#* #Html.ActionLink("View", "DisplayDetails")*#
#Html.ActionLink("View", "DisplayDetails")
</td>
</tr>
</table>
#Html.Action("DisplayDetails", "AddDetails");
}
Here is the partial view (Display view).
#model IList<mvcEmployeeTask.Models.AddDetails>
#{
Layout = null;
}
#using (Html.BeginForm("DisplayDetails", "AddDetails", FormMethod.Get))
{
<!DOCTYPE html>
<html>
<head>
<meta name="viewport" content="width=device-width" />
<title>DisplayDetails</title>
<link href="#Url.Content("~/Content/Site.css")" rel="stylesheet" type="text/css" />
</head>
<body> <div class="table" align="center">
<table border="1" >
<tr>
<th>EmployeeID</th>
<th>EmployeeName</th>
<th>Email</th>
</tr>
#foreach (var item in Model)
{
<tr>
<td>
#item.EmployeeId
</td>
<td>
#item.EmployeeName
</td>
<td>
#item.EmailId
</td>
<td>
#Html.ActionLink("Edit", "EditDetails", new { id= item.EmployeeId })
</td>
<td>
#Html.ActionLink("Delete", "DeleteDetails", new { id= item.EmployeeId })
</td>
</tr>
}
</table>
</div>
</body>
</html>
}
Please Help me!!
You should use
#Ajax.ActionLink
Reason:
Ajax.ActionLink is much like Html.ActionLink counterpart, it also creates the hyperlink Click here but when user clicks it and have the JavaScript enabled browser, Ajax.ActionLink sends the asynchronous request instead of navigating to new URL. With Ajax.ActionLink we specify what controller’s action method to invoke and also specify what to do with the response coming back from the action method and it suits your case really well.
Instead of
#Html.ActionLink("View", "DisplayDetails")
Description:
It will render the partial view on the same index screen instead of opening new window.
Something like this
#Ajax.ActionLink(" ", "ViewDetails", "Auditor", new AjaxOptions { UpdateTargetId = "yourviewDiv"}) //yourviewdiv is id of div where you want to show your partial view onClick
Your Main View
#model mvcEmployeeTask.Models.AddDetails
<div id = "yourviewDiv">
// it will populate your partial view here.
</div>
<link href="#Url.Content("~/Content/Site.css")" rel="stylesheet" type="text/css" />
#using (Html.BeginForm("AddDetail", "AddDetails", FormMethod.Post))
{
#Ajax.ActionLink(" ", "ViewDetails", "Auditor", new AjaxOptions { UpdateTargetId = "yourviewDiv"})
}
load following div using its id on particular event(say button click of your main view) then partial view will be load on your main view.
<div id="loadpartialview">
#Html.Partial("_yourPartialViewName")
</div>
here is nice tutorial how to implement it:
http://mvc4beginner.com/Tutorial/MVC-Partial-Views.html
The simple version of code is
<div>
#Html.Partial("PartialView1", Model.partialModel)
</div>
Theory:
To have it dynamic you need to create ajax call to render the action on server and insert the result to the page.
the question how to implement this has been already answered here:
MVC Partial view with controller, ajax - how do I ge the partial controller to get data?

MVC Razor Validation not firing on textarea

i am having a problem with validating a form in MVC Razor the Binding class is the following based off an abstract class (there is no validation in the abstract class)
[GeminiDisplayName("You are about To reject the following Purchase Order", false)]
public class PORejected : PoApprovalItems
{
public PORejected() { }
[GeminiDisplayName("Rejection Reason")]
[Required(AllowEmptyStrings = false, ErrorMessage = "Rejection Reason is Required")]
public string RejectReason { get; set; }
public override bool IsApproved
{
get
{
return false;
}
}
}
and the view is as follows
#model Gemini.Models.PORejected
#section Head{
<script src="#Url.Content("~/Scripts/jquery.validate.js")" type="text/javascript"></script>
<script src="#Url.Content("~/Scripts/MicrosoftAjax.js")" type="text/javascript"></script>
<script src="#Url.Content("~/Scripts/MicrosoftMvcAjax.js")" type="text/javascript"></script>
<script src="#Url.Content("~/Scripts/MicrosoftMvcValidation.js")" type="text/javascript"></script>
<script src="#Url.Content("~/Scripts/PageScripts/_Approval.js")" type="text/javascript"></script>
}
#section TabHeader{
<li>Reject Approval for PO #Model.PO_Number</li>
}
#section TabContent{
#{
Html.EnableClientValidation();
}
<div id="ApprovalItem">
#{
#Html.ValidationSummary(false)
using (Html.BeginForm("Approve", "PO", FormMethod.Post))
{
#Html.Partial("Approval/ApprovalDetails", Model)
<div class="display-label">
<table width="100%" cellpadding="0" cellspacing="0" border="0">
<tr>
<td width="15%">
#Html.LabelFor(x => x.RejectReason)
</td>
<td>
#Html.TextAreaFor(x => x.RejectReason, new { #Class = "mceEditor required", #style = "width:60%;" })
#Html.ValidationMessageFor(x => x.RejectReason)
</td>
</tr>
</table>
<div style="float: right;">
<input type="button" value="Close" />
<input type="submit" value="Reject" />
</div>
</div>
Html.EndForm();
}
}
</div>
}
the thing is when i click the submit button it fires off before doing any validation even though it should validate
my question is what am i doing wrong?
UPDATED
found the answer eventually i was missing the following from the page.
<script src="#Url.Content("~/Scripts/jquery.validate.unobtrusive.js")" type="text/javascript"></script>
found the answer eventually i was missing the following from the page. <script src="#Url.Content("~/Scripts/jquery.validate.unobtrusive.js")" type="text/javascript"></script>
What is this line for?
Html.EnableClientValidation(false);
This disables client validation. Also, no need to set UnobtrusiveParameters on each view, set them once in web config.

Resources