I am trying to fill auto complete textbox based on dropdown selected value,
But unable to pass selected dropdown value as parameter to autocomplete url.Action()
Here is the code which I am using..
Dictionary<string, string> searchlist = new Dictionary<string, string>();
searchlist.Add("option1", "1");
searchlist.Add("option2", "2");
searchlist.Add("option3", "3");
searchlist.Add("option4", "4");
SelectList list = new SelectList(searchlist, "value", "key");
#Html.DropDownListFor(m => m.SearchType, list, new {#id="category", #class = "select" })
<script type="text/javascript">
$(document).ready(function () {
$("#category").change(function () {
var selectedVal = $("#category option:selected").text();
alert("You selected :" + selectedVal);
});
});
</script>
<input type="text" id="searchField" name="searchField" data-autocomplete-url="#Url.Action("Autocomplete", "Home", new { lang = Model.Language, cattype = selectedVal })" class="select" value="Search" onBlur="if(this.value == '') this.value = 'Search';" onFocus="if(this.value == 'Search') this.value = '';" />
<img src="#Url.Content("~/Content/images/magnifier.png")" alt="Search" title="Search" />
Please help me where am I going wrong.
Thanks in advance.
You should fire autocomplete when DDL change:
$(document).ready(function () {
$("#category").change(function () {
var selectedVal = $("#category option:selected").text();
//fire autocomlete
$('*[data-autocomplete-url]').each(function () {
$(this).autocomplete(
{
source: function (request, response) {
$.ajax({
url: $(this).attr('data-action'),
dataType: "json",
data: { lang : '#Model.Language', cattype : selectedVal },
success: function (data) {
response($.map(data, function (item) {
return {
label: item.Label,
value: item.Label,
realValue: item.Value
};
}));
},
});
},
minLength: 2,
select: function (event, ui) {
//do something
},
change: function (event, ui) {
if (!ui.item) {
this.value = '';
} else {
}
}
});
});
});
});
Related
I created a dropdown using the <select> HTML element. Now I want to call an action after user makes a selection from the list.
<select name="ddAircraft" id="ddAircraft" class="form-control form-select-sm form-select"
asp-items="#(new SelectList(ViewBag.ddaircraft,"id","name"))">
</select>
I would also like to know if user enter a value in a input box. Then I want to run a Javascript method. How I can do that?
I tried to do onClick but I am getting usual error.
It would help if you could show the details of your error,
I Tried with the codes below:
#{
var sel = new List<SelectListItem>()
{
new SelectListItem(){Text="1",Value="1" },
new SelectListItem(){Text="2",Value="2" },
new SelectListItem(){Text="3",Value="3" }
};
}
<script src="~/lib/jquery/dist/jquery.min.js"></script>
<script>
$(function () {
$('#selectlist').change(function () {
window.location.href = "Privacy";
})
});
</script>
<script>
$(function () {
$('#input').change(function () {
window.location.href = "Privacy";
})
});
</script>
<input id="input" value=""></input>
<select id="selectlist" asp-items=sel></select>
The result:
To pass the selected item value ,you could try :
<script>
$(function () {
$('#selectlist').change(function () {
window.location.href = "Home/Privacy?sel=" + $(this).val();
})
});
</script>
The result:
if you want to make a post request, you could try with ajax as below:
<script>
$(function () {
$('#selectlist').change(function () {
var sel = $(this).val();
var input = document.getElementById("input").value;
$.ajax({
url: "Home/Test",
contentType: "application / json; charset = utf - 8",
type: "post",
data: JSON.stringify({
sel: sel,
input: input
}),
datatype: "json",
success: function (data) {
console.log(data);
}
})
})
});
</script>
The result:
I tried to use datatable with my project and I always got undefined when data return from the controller while I checked the controller already returned 1000 records
this is my controller
[HttpGet]
public JsonResult get_Student_Info()
{
var model = (from C in _db1.ClassesInfos
select new Classes
{
ClassId = C.Id,
ClassCounty = C.ClassCounty ?? "",
ClassLocation = C.ClassLocation,
ClassSize = C.ClassSize ?? 0,
ClassDate = C.ClassDate.ToString(),
//ClassMonitorId = C.MonitorId,
//ClassActive = C.Active ?? 0,
//ClassLastModifedDate = C.LastModifiedDate.ToString(),
//ClassPasscode = C.Passcode,
//ClassType = C.ClassType
}).FirstOrDefault();
return Json(mymodel, System.Web.Mvc.JsonRequestBehavior.AllowGet);
}
and this is my view
$(function () {
$.ajax({
type: "GET",
//url: "/Instructor/get_Student_Info",
url: '#Url.Action("get_Student_Info", "Instructor")',
mimeType: 'json',
async: true,
success: function(data) {
$.each(data, function (i, data) {
alert(data.ClassCounty);
alert(data.ClassLocation);
var body = "<tr>";
body += "<td>" + data.ClassCounty + "</td>";
body += "<td>" + data.ClassLocation + "</td>";
body += "</tr>";
$( "#ClasssInfo tbody" ).append(body);
});
/*DataTables instantiation.*/
$( "#ClasssInfo" ).DataTable();
},
});
});
In asp.net mvc, it should be:
Model:
public class Class
{
public string ClassCounty { get; set; }
public string ClassLocation { get; set; }
}
View:
<table id="ClasssInfo">
<thead>
<tr>
<th>ClassCounty</th>
<th>ClassLocation</th>
</tr>
</thead>
<tbody></tbody>
</table>
#section Scripts
{
<link rel="stylesheet" type="text/css" href="https://cdn.datatables.net/1.10.20/css/jquery.dataTables.css">
<script type="text/javascript" charset="utf8" src="https://cdn.datatables.net/1.10.20/js/jquery.dataTables.js"></script>
<script>
$(function () {
$.ajax({
type: "GET",
url: "#Url.Action("get_Student_Info", "Home")",
mimeType: 'json',
async: true,
success: function (data) {
$("#ClasssInfo").DataTable({
data: data,
columns: [{ 'data': 'ClassCounty' },
{ 'data': 'ClassLocation' }]
});
},
});
});
</script>
}
Controller:
public JsonResult get_Student_Info()
{
//must be list model
var model = new List<Class>(){
new Class()
{
ClassCounty = "aa",
ClassLocation = "location"
}
};
return Json(model, JsonRequestBehavior.AllowGet);
}
In asp.net core/.net 5, it should be:
View:
Note: In asp.net core/.net 5, the response json format is camel case.
<table id="ClasssInfo">
<thead>
<tr>
<th>ClassCounty</th>
<th>ClassLocation</th>
</tr>
</thead>
<tbody></tbody>
</table>
#section Scripts
{
<link rel="stylesheet" type="text/css" href="https://cdn.datatables.net/1.10.20/css/jquery.dataTables.css">
<script type="text/javascript" charset="utf8" src="https://cdn.datatables.net/1.10.20/js/jquery.dataTables.js"></script>
<script>
$(function () {
$.ajax({
type: "GET",
url: "#Url.Action("get_Student_Info", "Home")",
mimeType: 'json',
async: true,
success: function (data) {
$("#ClasssInfo").DataTable({
data: data,
columns: [{ 'data': 'classCounty' }, //difference here..should be camel case
{ 'data': 'classLocation' }]
});
},
});
});
</script>
}
Controller:
public JsonResult get_Student_Info()
{
var model = new List<Class>(){
new Class()
{
ClassCounty = "aa",
ClassLocation = "location"
}
};
return Json(model);
}
I'm working on autocomplete JQuery function to populate student names in the text box. I've utilized every related JQuery library to make the autocomplete function work. When i press F12, it always throws an error which is "autocomplete is not a function". Below is my code that I'm running.
StudentBatch.cshtml
<script src="https://code.jquery.com/jquery-1.12.4.js"></script>
<script src="https://code.jquery.com/ui/1.12.1/jquery-ui.js"></script>
<link rel="stylesheet" href="//code.jquery.com/ui/1.12.1/themes/base/jquery-ui.css">
<div class="form-group">
<div class="col-md-12">
#Html.EditorFor(model => model.StudentName, new { id = "StudentName" })
</div>
</div>
<script type="text/javascript">
$(document).ready(function () {
alert("This is autocomplete function");
});
$(document).ready(function () {
$("#StudentName").autocomplete({
//autocomplete: {
// delay: 0,
// minLength: 1,
source: function (request, response) {
$.ajax({
url: "/Student/Create",
type: "POST",
dataType: "json",
data: { Prefix: request.term },
success: function (data) {
try {
response($.map(data, function (item) {
return { label: item.StudentName, value: item.StudentName };
}))
} catch (err) { }
}
})
},
messages: {
noResults: "jhh", results: "jhjh"
}
});
});
</script>
StudentController.cs
[HttpPost]
public JsonResult Create(string Prefix)
{
CreateUser user = new CreateUser();
string stdid = "fae30ef0-08b2-4490-a389-3c8eb0a7cc53";
var StudentList = user.GetAllUsers().ToList().Where(u => u.FirstName == Prefix && u.usertypeid == stdid).ToString();
return Json(StudentList, JsonRequestBehavior.AllowGet);
}
I have created similar demo which you are creating.
Model
public class CreateUser
{
public string StudentName { get; set; }
public string StudentId { get; set; }
}
Controller
public class StudentController : Controller
{
// GET: Student
public ActionResult Create()
{
return View();
}
[HttpPost]
public JsonResult Create(string prefix)
{
List<CreateUser> studentList = new List<Models.CreateUser>()
{
new CreateUser { StudentId = "1" , StudentName = "Student1"},
new CreateUser { StudentId = "2" , StudentName = "Student2"},
new CreateUser { StudentId = "3" , StudentName = "Student3"},
new CreateUser { StudentId = "4" , StudentName = "Student4"},
new CreateUser { StudentId = "5" , StudentName = "Student5"},
new CreateUser { StudentId = "6" , StudentName = "Student6"},
new CreateUser { StudentId = "7" , StudentName = "Student7"},
};
var searchlist = (from student in studentList
where student.StudentName.Contains(prefix)
select student).ToList();
return Json(searchlist, JsonRequestBehavior.AllowGet);
}
}
View
#model WebApplication6.Models.CreateUser
#{
Layout = null;
}
<script src="http://ajax.aspnetcdn.com/ajax/jQuery/jquery-1.10.0.min.js" type="text/javascript"></script>
<script src="http://ajax.aspnetcdn.com/ajax/jquery.ui/1.9.2/jquery-ui.min.js" type="text/javascript"></script>
<link href="http://ajax.aspnetcdn.com/ajax/jquery.ui/1.9.2/themes/blitzer/jquery-ui.css" rel="Stylesheet" type="text/css" />
<style>
.ui-autocomplete {
max-height: 100px;
overflow-y: auto;
/* prevent horizontal scrollbar */
overflow-x: hidden;
}
/* IE 6 doesn't support max-height
* we use height instead, but this forces the menu to always be this tall
*/
* html .ui-autocomplete {
height: 100px;
}
.ui-autocomplete-input {
width: 300px;
}
</style>
<div class="form-group">
<div class="col-md-12">
#Html.EditorFor(model => model.StudentName, new { id = "StudentName" })
</div>
</div>
<script type="text/javascript">
$(document).ready(function () {
$("#StudentName").autocomplete({
//autocomplete: {
// delay: 0,
// minLength: 1,
source: function (request, response)
{
$.ajax({
url: "/Student/Create",
type: "POST",
dataType: "json",
data: { prefix: request.term },
success: function(data) {
try {
response($.map(data,
function (item)
{
return { label: item.StudentName, value: item.StudentName };
}));
} catch (err) {
}
}
});
},
messages:
{
noResults: "jhh", results: "jhjh"
}
});
});
</script>
Output
When i use ajax to post the form data to controller, i cannot get the files when using Kendo upload. I used IEnumerable but i only can get the date value and the file is null. May i know how to make it work? Thanks.
(I use ajax because i need call the onsuccess event)
//Here is the form control in view
<div class="editForm">
#using (Html.BeginForm("UpdateReportFix", "Defect", FormMethod.Post, new { id = "form" }))
{
#Html.HiddenFor(model => model.DefectFixID)
<div>
#Html.Label("Report Date")
</div>
<div>
#(Html.Kendo().DatePickerFor(model => model.ReportDate)
.Name("ReportDate")
.Value(DateTime.Now).Format("dd/MM/yyyy")
.HtmlAttributes(new { #class = "EditFormField" })
)
#Html.ValidationMessageFor(model => model.ReportDate)
</div>
<div>
#Html.Label("Photos")
<br />
<span class="PhotosMessage">System Allow 2 Pictures</span>
</div>
<div class="k-content">
#(Html.Kendo().Upload()
.Name("files") <-----i cannot get this value in controller
)
</div>
<br />
<div class="col-md-12 tFIx no-padding">
#(Html.Kendo().Button().Name("Cancel").Content("Cancel").SpriteCssClass("k-icon k-i-close"))
#(Html.Kendo().Button().Name("submit").Content("Submit").SpriteCssClass("k-icon k-i-tick"))
</div>
}
//script
$('form').submit(function (e) {
e.preventDefault();
var frm = $('#form');
$.ajax({
url: '#Url.Action("UpdateReportFix")',
type: 'POST',
data: frm.serialize(),
beforeSend: function () {
},
onsuccess: function () { },
success: function (result) { },
error: function () { }
});
});
For "Uploading files using Ajax & Retain model values after Ajax call and Return TempData as JSON" try the following example:
View:
#using (Html.BeginForm("Create", "Issue", FormMethod.Post,
new { id = "frmCreate", enctype = "multipart/form-data" }))
{
<div id="divMessage" class="empty-alert"></div>
#Html.LabelFor(m => m.FileAttachments, new { #class = "editor-label" })
#(Html.Kendo().Upload()
.HtmlAttributes(new { #class = "editor-field" })
.Name("files")
)
}
<script>
$(function () {
//Populate model values of the partialview after form reloaded (in case there is a problem and returns from Controller after Submit)
$('form').submit(function (event) {
event.preventDefault();
showKendoLoading();
var selectedProjectId = $('#ProjectID').val(); /* Get the selected value of dropdownlist */
if (selectedProjectId != 0) {
//var formdata = JSON.stringify(#Model); //For posting uploaded files use as below instead of this
var formdata = new FormData($('#frmCreate').get(0));
$.ajax({
type: "POST",
url: '#Url.Action("Create", "Issue")',
//contentType: "application/json; charset=utf-8", //For posting uploaded files use as below instead of this
data: formdata,
dataType: "json",
processData: false, //For posting uploaded files we add this
contentType: false, //For posting uploaded files we add this
success: function (response) {
if (response.success) {
window.location.href = response.url;
#*window.location.href = '#Url.Action("Completed", "Issue", new { /* params */ })';*#
}
else if (!response.success) {
hideKendoLoading();
//Scroll top of the page and div over a period of one second (1,000 milliseconds = 1 second).
$('html, body').animate({ scrollTop: (0) }, 1000);
$('#popupDiv').animate({ scrollTop: (0) }, 1000);
var errorMsg = response.message;
$('#divMessage').html(errorMsg).attr('class', 'alert alert-danger fade in');
$('#divMessage').show();
}
else {
var errorMsg = null;
$('#divMessage').html(errorMsg).attr('class', 'empty-alert');
$('#divMessage').hide();
}
}
});
}
else {
$('#partialPlaceHolder').html(""); //Clear div
}
});
});
</script>
Controller:
[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult Create([Bind(Exclude = null)] Model viewModel, IEnumerable<HttpPostedFileBase> files)
{
//...
return Json(new { success = false, message = "Max. file size is 10MB" }, JsonRequestBehavior.AllowGet);
}
i have the follow MVC View
#model Site.SupportItems.SiteAditionalInformation
#using Site.Helpers.Extenders;
#{
Response.CacheControl = "no-cache";
}
<div>
#using (Html.BeginForm("SaveSiteAdditionalInformation", "Support", FormMethod.Post, new { #Id = "frmSiteInformation" }))
{
#Html.ValidationSummary(true)
<fieldset>
<legend>Site Aditional Information</legend>
<div class="site-PO-footer-outline-left-comment">
<div class="site-item-outline">
<div class="site-label-left ui-corner-all">
#Html.LabelFor(model => model.Office)
</div>
<div class="site-detail">
#Html.DropDownListFor(x => x.Office, Model.Offices.ToSelectList("ValueSelected", "DisplayValueSelected", Model.Office))
#Html.ValidationMessageFor(model => model.Office)
</div>
</div>
<div class="site-item-outline">
<div class="site-label-left ui-corner-all">
#Html.LabelFor(model => model.AdditionalInformation)
</div>
<div class="site-detail">
#Html.TextAreaFor(model => model.AdditionalInformation, new { #Class = "ui-site-rtb" })
#Html.ValidationMessageFor(model => model.AdditionalInformation)
</div>
</div>
</div>
<p>
<input type="submit" value="Save" id="btnSubmit" />
</p>
</fieldset>
}
<script type="text/javascript">
$(function ()
{
var thisTab = $(Globals.ActiveTabId());
var previousSelectedOffice;
$('#Office', thisTab).click(function ()
{
previousSelectedOffice = $('#Office', thisTab).val();
}).change(function (e)
{
var setNewContent = function ()
{
$('#loading-Panel').Loading('show');
$.ajax('#Url.Action("GetSiteSpecificText")', {
data: { Office: $('#Office', thisTab).val(),
rnd: Math.random() * 10000
},
cached: false,
success: function (response)
{
if (response != null)
{
$('#AdditionalInformation', thisTab).html(response);
}
else
$('#AdditionalInformation', thisTab).html('');
$('#loading-Panel').Loading('hide');
}
});
};
if (tinyMCE.activeEditor.isDirty())
{
$('<div/>').text('The Text has changed for the Additional Information. Would you like to save?').dialog({
title: 'Text has Changed',
buttons: {
'Ok': function ()
{
$('#loading-Panel').Loading('show');
var beforeSave = $('#Office', thisTab).val();
$('#Office', thisTab).val(previousSelectedOffice);
$('#frmSiteInformation', thisTab).trigger('submit');
$('#Office', thisTab).val(beforeSave);
setNewContent();
$(this).dialog('close');
},
'Cancel': function ()
{
$(this).dialog('close');
$('#Office', thisTab).val(previousSelectedOffice);
}
}
});
}
else
{
setNewContent();
}
});
$('#frmSiteInformation', thisTab).submit(function ()
{
tinyMCE.triggerSave();
var data = $('#frmSiteInformation', thisTab).serializeObject();
$('#loading-Panel').Loading('show');
$.ajax($(this).attr('action'), {
type: 'POST',
dataType: 'json',
contentType: 'application/json; charset=utf-8',
data: JSON.stringify(data),
success: function (data)
{
if (data.SaveResult)
$('<div/>').text('Save Successful for' + $('#Office option:selected', thisTab).text())
.dialog({
title: 'Save Successful',
buttons: {
'Ok': function ()
{
$(this).dialog('close');
}
}
});
$('#loading-Panel').Loading('hide');
}
});
return false;
});
});
</script>
</div>
and while most of it is doing what i expect if i change the dropdown i want to clear the RTB back to nothing (or the response value if there is one from the DB)
while this is working if i change the dropdown again the tinyMCE.activeEditor.isDirty() is always coming back as true when i believe it should be false.
i have tried tinymce.execCommand('mceToggleEditor',false,'AdditionalInformation');
but this only reloads the first RTB
and also tinymce.execCommand('mceRemoveEditor',false,'AdditionalInformation');
which causes an error.
if anyone could point me in the right direction i would really appreciate it.
thanks.
Edit I have solved the problem i am having using the mceRemoveEditor command
the function call for setNewContent is as follows
var setNewContent = function ()
{
$('#loading-Panel').Loading('show');
$.ajax('#Url.Action("GetSiteSpecificText")', {
data: { Office: $('#Office', thisTab).val(),
rnd: Math.random() * 10000
},
cached: false,
success: function (response)
{
tinymce.execCommand('mceRemoveEditor', false, 'AdditionalInformation');
if (response != null)
{
$('#AdditionalInformation', thisTab).html(response);
}
else
$('#AdditionalInformation', thisTab).html('');
tinymce.execCommand('mceAddControl', false, 'AdditionalInformation');
$('#loading-Panel').Loading('hide');
}
});
};
Thanks for the help.