I have one field in my view, it is a textbox field. But I'd like to change that field to an Autocomplete dropdown.
Below is my view:
#Html.TextBoxFor(model => model.SearchFilterPaymentCode, new { #class = "form-control", #id = "searchInput1" })
#Html.HiddenFor(model => model.ID)
<script>
$(document).ready(function () {
$("#searchInput1").autocomplete({
source: function (request, response) {
$.ajax({
url: '#Url.Action("getJenisPembayaran", "Payment1")',
dataType: "json",
data: {
term: request.term
},
success: function (data) {
response($.map(data, function (val, item) {
return {
label: val.Name,
value: val.Name,
ID: val.ID
}
}))
}
})
},
select: function (event, ui) {
$("#ID").val(ui.item.ID);
$("#SearchFilterPaymentCode").val(ui.item.label);
}
});
})
</script>
and below is my controller
public JsonResult getJenisPembayaran(string term)
{
var objCustomerlist = db.ParamJenisPembayarans.Where(x => x.Name.ToUpper()
.Contains(term.ToUpper()))
.Select(x => new ParamJenisPembayaranViewModel
{
ID = x.ID,
JenisPembayaran = x.Name
}).Distinct().ToList();
return Json(objCustomerlist, JsonRequestBehavior.AllowGet);
}
When I debug the controller and fill the textbox with a few words, I get some data from the database, that means the controller is working well but the data does not appear in the view. What's wrong with my code?
Related
I getting name perfectly but I am not getting their name related ID in ajax autocomplete
Following is the view code,
#Html.TextBoxFor(model => Model.CustomerFullName, new { #class = "form-control" })
#Html.TextAreaFor(model => Model.CustomerId)
$(document).ready(function () {
$("#CustomerFullName").autocomplete({
source: function (request, response) {
$.ajax({
url: '#Url.Action("AutoComplete", "Order")',
datatype: "json",
data: {
term: request.term
},
success: function (data) {
response($.map(data, function (val) {
return {
value: val.Name,
label: val.Name
}
}))
}
})
},
select: function (event, ui) {
alert(ui.item.id);
$("#CustomerId").val(ui.item.id);
}
});
});
Here is the controller,
public JsonResult AutoComplete(string term = "")
{
var objCustomerlist = (from customer in _customerRepository.Table
where customer.Username.StartsWith(term)
select new
{
Name = customer.Username,
ID = customer.Id
}).ToList();
return Json(objCustomerlist);
}
In autocomplete ajax select section alert showing undefined
I tried things to solve like
JSON.Stringfy(ui.item.id)
ui.id
but still didnt work.
I am getting autocomplete item list from javascript autocomplete but when I select that autocomplete item list at that time it shows the error i.e. Uncaught TypeError: n.item is undefined
Here is my code,
<div class="form-group">
<div class="col-md-3">
<nop-label asp-for="Name" />
</div>
<div class="col-md-9">
#Html.TextBoxFor(model => Model.Name, new { #class = "form-control" })
#Html.HiddenFor(model => Model.Name)
</div>
</div>
$(document).ready(function () {
$("#Name").autocomplete({
source: function (request, response) {
$.ajax({
url: '#Url.Action("AutoComplete", "Product")',
datatype: "json",
data: {
term: request.term
},
success: function (data) {
response($.map(data, function (val) {
return {
label: val.Name,
value: val.Name
}
}))
}
})
},
select: function (ui) {
$("#Name").val(ui.item.Name);
}
});
});
Here is the controller
public JsonResult AutoComplete(string term = "")
{
var objCustomerlist = (from product in _productMasterRepository.Table
where product.Name.StartsWith(term)
select new
{
Name = product.Name,
ID = product.Name
}).ToList();
return Json(objCustomerlist);
}
Your select signature is incorrect:
select: function (ui) {
$("#Name").val(ui.item.Name);
}
Change it into:
select: function (event, ui) {
$("#Name").val(ui.item.Name);
}
And that should work fine.
controller:
[HttpPost]
public JsonResult Index(string search)
{
var data = LoadExplore_SP("sp_View_Explore");
List<ExploreModel> stuff = new List<ExploreModel>();
foreach (var row in data)
{
stuff.Add(new ExploreModel
{
Thing_Title = row.Thing_Title
});
}
//Searching records from list using LINQ query
var ThingList = (from N in stuff
where N.Thing_Title.Contains(search)
select new { N.Thing_Title });
return Json(ThingList, JsonRequestBehavior.AllowGet);
}
view:
<script type="text/javascript">
$(document).ready(function () {
$("#Thing_Title").autocomplete({
source: function (request, response) {
$.ajax({
url: "/Home/Index",
type: "POST",
dataType: "json",
data: { search: request.term },
success: function (data) {
response($.map(data, function (item) {
return { label: item.Thing_Title, value: item.Thing_Title };
}))
}
})
},
messages: {
noResults: "", results: ""
}
});
})
#using (Html.BeginForm())
{
#Html.AntiForgeryToken()
<div class="form-horizontal">
<hr />
<div class="form-group">
<div class="col-md-12">
#Html.EditorFor(model => model.Thing_Title, new { htmlAttributes = new { #class = "form-control" } })
</div>
</div>
</div>
}
My problem is that I can't get the linq where clause to work the way it should. Instead of returning results like %search%, it is returning all records like 'search%' instead.
Do you know why it's behaving this way?
I have a slight problem with ajax. So first I'm gonna show you my actions.
Form:
<form id="QuestionForm">
#Html.TextBoxFor(model => model.Body, new { #class = "form-control", #placeholder = "Body" })
#Html.TextBoxFor(model => model.Text, new { #class = "form-control", #placeholder = "Text" })
</form>
Here's my script and ajax code:
$("#btnSubmit").click(function () {
var data = $('#QuestionForm').serialize();
$.ajax({
type: "POST",
url: "/Survey/AddQuestion",
data: {data, #Model.Survey.Id},
success: function () {
$("#AddQuestion").modal("hide");
//alert("Survey Added");
location.reload();
}
})
})
Here's my controller action:
public JsonResult AddQuestion(SurveyQuestion model, int id)
{
SurveyQuestion question = new SurveyQuestion();
question.Body = model.Body;
question.CreatedOn = DateTime.Now;
question.ModifiedOn = DateTime.Now;
question.Priority = 0;
question.SurveyId = id;
question.Text = model.Text;
question.Type = QuestionType.Text;
_db.SurveyQuestions.Add(question);
_db.SaveChanges();
return Json(question, JsonRequestBehavior.AllowGet);
}
I didn't fill out every part of the code, some of it is hardcoded, because I'm going to do the actions later. But the problem is with sending two things.
If I don't send the Id and delete Id from the controller, it sends the serialized model well, but If I send them both, it gets the Id, but it doesn't get the model sent to him (text and body is null). How do I fix this?
You can do it like below:
$("#btnSubmit").click(function() {
$.ajax({
type: "POST",
url: "/Survey/AddQuestion",
// Add id like query string parameter like below
data: $('#QuestionForm').serialize() + '&id=' + #Model.Survey.Id,
success: function() {
$("#AddQuestion").modal("hide");
//alert("Survey Added");
location.reload();
}
})
})
Pass id as query string parameter
$("#btnSubmit").click(function () {
var data = $('#QuestionForm').serialize();
$.ajax({
type: "POST",
url: "/Survey/AddQuestion?id=" + '#Model.Survey.Id',
data: {data, #Model.Survey.Id},
success: function () {
$("#AddQuestion").modal("hide");
//alert("Survey Added");
location.reload();
}
})
})
In controller use FromUri attribute before the parameter
public JsonResult AddQuestion(SurveyQuestion model,[FromUri]int id)
{
SurveyQuestion question = new SurveyQuestion();
question.Body = model.Body;
question.CreatedOn = DateTime.Now;
question.ModifiedOn = DateTime.Now;
question.Priority = 0;
question.SurveyId = id;
question.Text = model.Text;
question.Type = QuestionType.Text;
_db.SurveyQuestions.Add(question);
_db.SaveChanges();
return Json(question, JsonRequestBehavior.AllowGet);
}
Try this, passing multiple parameters in post or you can pass using querystring as shown in other answers
$("#btnSubmit").click(function () {
var data = $('#QuestionForm').serialize();
$.ajax({
type: "POST",
url: "/Survey/AddQuestion",
data: {model : data, id: #Model.Survey.Id},
success: function () {
$("#AddQuestion").modal("hide");
//alert("Survey Added");
location.reload();
}
})
})
Controller
public ActionResult ActionName(SurveyQuestion model, int id)
{
Your Code .......
}
you can put id in the url
$("#btnSubmit").click(function () {
var data = $('#QuestionForm').serialize();
$.ajax({
type: "POST",
url: "/Survey/AddQuestion?id=#Model.Survey.Id",
data: {data},
success: function () {
$("#AddQuestion").modal("hide");
//alert("Survey Added");
location.reload();
}
})
})
I have my textboxfor field which select the data from role table from the database
i need this textboxfor field make a autocomplete with starting character.
Sample:
MVC code:
This JsonResult in the UsersControl
public JsonResult GetRoles(string Prefix)
{
var RoleListVal = db.Roles.Where(r => r.Deleted == false)
.Where(r => r.Name.ToUpper().StartsWith(Prefix))
.Select(r => new { Name = r.Name, ID = r.RoleID }).Distinct().ToList();
return Json(RoleListVal, JsonRequestBehavior.AllowGet);
}
cshtml Code:
This the JS and the HTML5 TextBoxFor:
$("#keywords-manual").autocomplete({
source: "/Users/GetRoles",
minLength: 1
})
<div class="form-inline">
#Html.Label("Role :")
#Html.TextBoxFor(model => model.Roles.FirstOrDefault().Name, new { #class = "form-control", #id = "keywords-manual" })
</div>
I don't why isn't working!
Here your controller side method looks good.
But issue is while you calling method.
$("#keywords-manual").autocomplete({
source: function (request, response) {
$.ajax(
{
type: "POST",
url: '#Url.Action("GetRoles","Users")',
data: { Prefix: $('#keywords-manual').val() },
dataType: "json",
success: function (data) {
response($.map(data, function (item) {
return {
value: item.Name,
description: item
}
}))
},
error: function (error) {
console.log(error);
}
});
},
minLength: 1,
select: function (event, ui) {
}
});
This is how you configure the Autocomplete plug in
On HTML Side:
$(function () {
$("#keywords-manual").autocomplete({
source: "#Url.Action("GetRoles","Users")",
minLength: 1
})
});
On the controller side:
public JsonResult GetRoles(string term)
{
var RoleListVal = db.Roles.Where(r => r.Deleted == false)
.Where(r => r.Name.ToUpper().StartsWith(term))
.Select(r => new { label = r.Name, id = r.RoleID,value=r.RoleID }).Distinct().ToList();
return Json(RoleListVal, JsonRequestBehavior.AllowGet);
}