My javascript is getting locked after ajax call.
When the user press enter then i call my c# method to search the city that the user typed, and then show the temperature, but when the search ends, the javascript stops working. And i found out that the error is on these lines:
var div = document.getElementById('rb-grid');
div.innerHTML = resp.responseText + div.innerHTML;
code:
$(document).ready(function () {
$('#search-bar').keyup(function (event) {
if (event.keyCode == 13) {
myFunction();
}
});
function myFunction() {
var city = $('#search-bar').val();
$.ajax({
url: '#Url.Action("getWeatherSearch", "Index")',
data: { city: city },
async: false,
complete: function (resp) {
var div = document.getElementById('rb-grid');
div.innerHTML = resp.responseText + div.innerHTML;
Boxgrid.init();
}
});
} });
HTML:
<div align="center" class="div-search-bar">
#Html.TextBox("search-bar", "", new { #class = "search-bar", placeholder = "search" })
</div>
Try the following and see if it works for you:
$(function () {
var $searchbar = $('#search-bar'),
$grid = $('#rb-grid');
if ($grid.length) {
$searchbar.on('keyup', function (event) {
if (event.keyCode == 13) {
myFunction();
}
});
function myFunction() {
var city = $searchbar.val();
$.ajax({
url: $.grid.data('weather-url'),
data: { city: city }
})
.done(function (resp) {
$grid.html(resp.responseText + $grid.html());
Boxgrid.init();
}
});
}
}
});
Add the following as a data attribute somewhere in your html, probably on your grid:
<div id='rb-grid' data-weather-url='#Url.Action("getWeatherSearch", "Index")'></div>
Related
I have implemented Cascading (Dependent) DropDownList using ASP.NET MVC.
This is the tutorial
Now I need show alert message box after insert data and redirect on Index page in ASP.NET MVC.
To show alert message in ASP.NET MVC after insert data using store procedure from MySQL database, I have write the code like as shown below.
<script type="text/javascript">
$(function () {
var msg = '#ViewData["result"]';
if (msg > 0)
{
alert("User Details Inserted Successfully");
window.location.href = "#Url.Action("Index", "Home")";
}
});
</script>
The data is correctly registered in the database table and the alert message box after insert data it's show.
But the redirect to index.cshtml not working because all the DropDownList on the form are empty except the first DropDownList that populates correctly.
window.location.href = "#Url.Action("Index", "Home")";
I mean that all other (populated cascading) DropDownList are enabled but empty.
I need redirect to Index Action page and being able to reload a new record, with this redirection it is impossible because the populated cascading DropDownList remain empty... instead of disabled and populated from value of first dropdownlist...
How to do resolve this?
Thanks.
Update 2021-01-02
#section Scripts {
#Scripts.Render("~/bundles/jqueryui")
#Scripts.Render("~/bundles/jqueryval")
#Scripts.Render("~/Scripts/DatePicker.js");
#Styles.Render("~/Content/cssjqryUi")
<script type="text/javascript">
$(function () {
var msg = '#ViewData["result"]';
console.log(msg);
if (msg > 0)
{
alert("User Details Inserted Successfully");
var url = "#Url.Action("Index", "Home")";
window.location.href = url;
}
});
</script>
<script src="Scripts/jquery-1.10.2.js"></script>
<script type="text/javascript">
jQuery(function ($) {
$.validator.addMethod('date',
function (value, element) {
if (this.optional(element)) {
return true;
}
var ok = true;
try {
$.datepicker.parseDate('dd/mm/yy', value);
}
catch (err) {
ok = false;
}
return ok;
});
$("#thedate").datepicker(options);
$(function () {
$(".loading").hide();
$("select").each(function () {
if ($(this).find("option").length <= 1) {
$(this).attr("disabled", "disabled");
}
});
$("select").change(function () {
var value = 0;
if ($(this).val() != "") {
value = $(this).val();
}
var id = $(this).attr("id");
$.ajax({
type: "POST",
url: "/Home/AjaxMethod",
data: '{type: "' + id + '", value: "' + value + '"}',
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (response) {
var dropDownId;
var list;
switch (id) {
case "CountryId":
list = response.States;
DisableDropDown("#TicketId");
DisableDropDown("#CityId");
dropDownId = "#TicketId";
list = response.Ticket;
PopulateDropDown("#TicketId", list);
break;
case "TicketId":
list = response.States;
DisableDropDown("#StateId");
PopulateDropDown("#StateId", list);
break;
case "StateId":
dropDownId = "#CityId";
list = response.Cities;
DisableDropDown("#CityId");
PopulateDropDown("#CityId", list);
dropDownId = "#CityId2";
list = response.Cities2;
PopulateDropDown("#CityId2", list);
$("#GPS").val(response.GPS);
break;
}
},
failure: function (response) {
alert(response.responseText);
},
error: function (response) {
alert(response.responseText);
}
});
});
});
function DisableDropDown(dropDownId) {
$(dropDownId).attr("disabled", "disabled");
$(dropDownId).empty().append('<option selected="selected" value="">[ === Select === ]</option>');
}
function PopulateDropDown(dropDownId, list) {
var modal = $('<div />');
modal.addClass("modalBackground");
$('body').append(modal);
var loading = $(".loading");
loading.show();
var top = Math.max($(window).height() / 2 - loading[0].offsetHeight / 2, 0);
var left = Math.max($(window).width() / 2 - loading[0].offsetWidth / 2, 0);
loading.css({ top: top, left: left });
setTimeout(function () {
if (list != null && list.length > 0) {
$(dropDownId).removeAttr("disabled");
$.each(list, function () {
$(dropDownId).append($("<option></option>").val(this['Value']).html(this['Text']));
});
$(".loading").hide();
$('.modalBackground').remove();
}
}, 1000);
}
</script>
}
update controller
[HttpPost]
public ActionResult Index(PersonModel person)
{
MTsqlinsert(person); //Insert values in the database
if (ModelState.IsValid)
{
PersonModel personModel = new PersonModel();
person.Countries = PopulateDropDown("SELECT CountryId, CountryName FROM Countries", "CountryName", "CountryId");
person.States = PopulateDropDown("SELECT StateId, StateName FROM States WHERE CountryId = " + countryId, "StateName", "StateId");
person.Cities = PopulateDropDown("SELECT CityId, CityName FROM Cities WHERE StateId = " + stateId, "CityName", "CityID");
ViewData["result"] = "1";
return RedirectToAction("Index");
}
return View(person);
}
[HttpGet]
[OutputCache(NoStore = true, Duration = 60, VaryByParam = "*")]
public ActionResult Index()
{
PersonModel personModel = new PersonModel
{
Countries = PopulateDropDown("SELECT CountryId, CountryName FROM Countries", "CountryName", "CountryId");
};
return View(personModel);
}
I need to populate Cascading Country, State and City DropDownLists using jQuery AJAX in ASP.Net MVC.
This is the tutorial
https://www.aspsnippets.com/Articles/Cascading-Dependent-Country-State-City-DropDownLists-using-jQuery-AJAX-in-ASPNet-MVC.aspx
And working correctly.
My problem is validate these DropDownList when send the form
#Html.DropDownListFor(m => m.CountryId, Model.Countries, "[ === Select CountryId === ]", new { #Class = "textarea" })
#Html.ValidationMessageFor(m => m.CountryId, "", new { #class = "text-danger" })
#Html.DropDownListFor(m => m.StateId, Model.States, "[ === Select StateId === ]", new { #Class = "textarea" })
#Html.ValidationMessageFor(m => m.StateId, "", new { #class = "text-danger" })
In this moment if on the DropDownList no value is selected the form is validate.
How to do resolve this?
My View javascript part follow
#section Scripts {
<script src="https://code.jquery.com/jquery-1.10.2.js"
integrity="sha256-it5nQKHTz+34HijZJQkpNBIHsjpV8b6QzMJs9tmOBSo="
crossorigin="anonymous"></script>
<script type="text/javascript">
$(function () {
$("select").each(function () {
if ($(this).find("option").length <= 1) {
$(this).attr("disabled", "disabled");
}
});
$("select").change(function () {
var value = 0;
if ($(this).val() != "") {
value = $(this).val();
}
var id = $(this).attr("id");
$.ajax({
type: "POST",
url: "/Home/AjaxMethod",
data: '{type: "' + id + '", value: "' + value + '"}',
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (response) {
var dropDownId;
var list;
switch (id) {
case "CountryId":
list = response.States;
DisableDropDown("#StateId");
DisableDropDown("#CityId");
PopulateDropDown("#StateId", list);
break;
case "StateId":
dropDownId = "#CityId";
list = response.Cities;
DisableDropDown("#CityId");
PopulateDropDown("#CityId", list);
break;
}
},
failure: function (response) {
alert(response.responseText);
},
error: function (response) {
alert(response.responseText);
}
});
});
});
function DisableDropDown(dropDownId) {
$(dropDownId).attr("disabled", "disabled");
$(dropDownId).empty().append('<option>[ === Select CountryId === ]</option>');
}
function PopulateDropDown(dropDownId, list) {
if (list != null && list.length > 0) {
$(dropDownId).removeAttr("disabled");
$.each(list, function () {
$(dropDownId).append($("<option></option>").val(this['Value']).html(this['Text']));
});
}
}
</script>
}
Why not implement something like this:
if ($(this).val() == "") {
// return validation message
return;
}
else
{
value = $(this).val();
}
I have a dropdownlist contains a list of products which binds from database. I want to load selected product Data.
here is my code in view
#Html.DropDownListFor(model => model.ProductName, new SelectList(Model.ProductsList, "ProductID", "ProductName"), new
{
id = "Productslist",
#class = "GreenDropDownListStyle",
#datastyle = "dropdown",
#onchange = "FillProduct()"
})
I had use java Script code to send select Product Id then get it's data
<script type="text/javascript">
$(document).ready(function () {
$("#Productslist").change(function () {
debugger;
var selectedIndex = $(this).val();
var divH = document.getElementById(selectedIndex);
if (selectedIndex > 0) {
$.ajax(
{
url: '/Inventory/ViewProduct',
type: 'GET',
data: { ProductID: selectedIndex },
contentType: 'application/json; charset=utf-8',
success: function (data) {
///
},
error: function () {
alert("error");
}
});
}
else {
divH.style.visibility = 'hidden'; // Hide
}
});
});
</script>
the issue that this code send the selected index not the is for the selected product also its send the id as a string so it never go to my condition
last thing in case of succeed what i should write
it solved by
var ProductID = this.value;
I am trying to implement auto-populate on a particular textbox but it is not working so far. Here's my code. What am I missing?
VIEW:
<script type="text/javascript">
$(document).ready(function () {
$("#lead-organisation").autocomplete({
source: function (request, response) {
$.ajax({
url: "/Project/AutoCompleteOrganisation",
type: "POST",
dataType: "json",
data: { term: request.term },
success: function (data) {
response($.map(data, function (item) {
return { label: item.Organisation, value: item.Organisation };
}))
}
})
},
messages: {
noResults: "", results: ""
}
});
})
</script>
<div class="form-group">
<label for="#Html.IdFor(x => x.Organisation)">
#Html.DisplayNameFor(x => x.Organisation)
</label>
#Html.TextBoxFor(x => x.Organisation, new { #class = "form-control", data_project = "organisation", editorId="lead-organisation" })
#Html.ValidationMessageFor(x => x.Organisation)
</div>
My CONTROLLER:
[AjaxOnly]
public ActionResult AutoCompleteOrganisation(string term)
{
var taxonomy = DependencyResolver.Current.GetService<TaxonomyHelper>();
var organisationList = new ProjectOrganisationModel();
organisationList.Organisation = taxonomy.GetOrganisations();
var result = from org in organisationList.Organisation
where org.Name.ToLower().Contains(term.ToLower())
select org.Name;
return Json(result, "application/json", Encoding.UTF8, JsonRequestBehavior.AllowGet);
}
I have also downloaded this:jquery.autocomplete.js and added it on my BundleConfig.cs
.Include("~/Scripts/jquery.autocomplete.js")
I was able to finally make it work.
Used this instead:
<script type="text/javascript">
$(document).ready(function () {
$("#lead-organisation").autocomplete({
source: '#Url.Action("AutoCompleteOrganisation", "Project")'
});
})
</script>
For controller:
public JsonResult AutoCompleteOrganisation(string term)
{
var taxonomy = DependencyResolver.Current.GetService<TaxonomyHelper>();
var organisationList = new ProjectOrganisationModel();
organisationList.Organisation = taxonomy.GetOrganisations();
var match = organisationList.Organisation.Where(x => x.Name.ToLower().Contains(term.ToLower())).
Select(e => e.Name).Distinct().ToList();
return Json(match, JsonRequestBehavior.AllowGet);
}
Then I did not download any autocomplete plugin, instead just use:
jquery-ui-1.10.4.custom.css
jquery-ui-1.10.4.custom.js
jquery-2.1.1.js
Thank you for answering my queries.
I have got problem with displaying employee details in view when the user clicks the button on view..
when the user clicks the button the employee details(both id and name) will be called through the JSON and displaying data in html table, for that purpose I have written like this in my view
#Scripts.Render("~/bundles/jquery")
<script type="text/javascript">
$(function () {
$('#submitbtnn').click(function () {
var table = $('#parenttable');
var url = '/EmpDetails/GetEmployees/';
$.getJSON(url, function (data) {
$.each(data, function (key, Val) {
var user = '<tr><td>' + Val.EmployeeId + '<td><tr>' + '<tr><td>' + Val.EmployeeName + '<tr><td>'
table.append(user);
});
});
});
});
</script>
#{
ViewBag.Title = "GetEmployeesByName";
}
<h2>GetEmployeesByName</h2>
#using (Html.BeginForm())
{
<table id ="parenttable"></table>
<input id="submitbtnn" type="Submit" value="Submit1" />
}
and this is my controller, here i am returning json data to view
namespace MvcSampleApplication.Controllers
{
public class EmpDetailsController : Controller
{
[HttpGet]
public ActionResult GetEmployees()
{
List<EmployeeClass> employees = new List<EmployeeClass>();
EmployeeClass employee1 = new EmployeeClass { EmployeeId=1, EmployeeName = "Rams"};
EmployeeClass employee2 = new EmployeeClass { EmployeeId = 2, EmployeeName = "joseph" };
EmployeeClass employee3 = new EmployeeClass { EmployeeId = 3, EmployeeName = "matt" };
employees.Add(employee1);
employees.Add(employee2);
employees.Add(employee3);
return Json(employees, JsonRequestBehavior.AllowGet);
}
}
}
but I am getting http 404 resource not found error, when i am trying to access this url
http://localhost/EmpDetails
would any one pls suggest any ideas and any suggestions on this,that would be very greatful to me..
Many thanks...
Modified View
#Scripts.Render("~/bundles/jquery")
<script type="text/javascript">
$(function () {
$('#submitbtnn').click(function () {
var table = $('#parenttable');
var url = #Url.Action("GetEmployees","EmpDetails")
//alert("hi");
$.getJSON(url, function (data) {
//alert("hi");
$.each(data, function (Val) {
var user = '<tr><td>' + Val.EmployeeId + Val.EmployeeName + '<tr><td>'
table.append(user);
});
});
return false;
});
});
</script>
#{
ViewBag.Title = "GetEmployeesByName";
}
<h2>GetEmployeesByName</h2>
#using (Html.BeginForm())
{
<div class="temptable">
<table id ="parenttable"></table>
</div>
<input id="submitbtnn" type="Submit" value="Submit1" />
}
I am not able to hit second Alert Function inside JavaScript function.
You forgot to cancel the default action of the button by returning false from the click handler:
$('#submitbtnn').click(function () {
var table = $('#parenttable');
var url = '/EmpDetails/GetEmployees/';
$.getJSON(url, function (data) {
$.each(data, function (key, Val) {
var user = '<tr><td>' + Val.EmployeeId + '<td><tr>' + '<tr><td>' + Val.EmployeeName + '<tr><td>'
table.append(user);
});
});
return false; // <!-- This is very important
});
By not canceling the default action, when you click on the submit button, the browser submits the form and redirects away from the page to the action of the form leaving no time for the AJAX request to ever execute.
Try using this as your url #Url.Action("GetEmployees","EmpDetails")
Try this
$(function () {
$('#submitbtnn').click(function () {
var table = $('#parenttable');
$.ajax({
url: 'GetEmployees',
type: 'POST',
data: JSON.stringify({ table: table }),
dataType: 'json',
contentType: 'application/json',
success: function (data) {
var rowcount = data.employees.length;
for (var i = 0; i < rowcount; i++) {
var user = '<tr><td>' + employees[i].EmployeeId + employees[i].EmployeeName + '<tr><td>'
table.append(user);
}
});
},
error: function () {
alert('fail');
}
});
return false;
});