Why Javascript is not firing? [closed] - javascript

This question is unlikely to help any future visitors; it is only relevant to a small geographic area, a specific moment in time, or an extraordinarily narrow situation that is not generally applicable to the worldwide audience of the internet. For help making this question more broadly applicable, visit the help center.
Closed 9 years ago.
Why JavaScript is not working on this project? Can anyone tell me the reason why this is happening? I also comment the script links on my _Layout but still doesn't work.
The Model
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
namespace FA_CS.Models.Credit
{
public class CreditCarModel
{
public string SelectedProvinceId { get; set; }
public string SelectedCityId { get; set; }
public string SelectedSuburbId { get; set; }
public IEnumerable<Province> Provinceses { get; set; }
}
public class Province
{
public string Id {get;set;}
public string Name {get;set;}
}
}
Here is the View
This is the view of my project and the internal and external JS in this project.
#model FA_CS.Models.Credit.CreditCarModel
#{
ViewBag.Title = "Spider";
}
<script type="text/javascript" src="/scripts/jquery-1.4.4.js"></script>
<script type="text/javascript">
$(function () {
$('#SelectedProvinceId').change(function () {
var selectedProvinceId = $(this).val();
$.getJSON('#Url.Action("Cities")', { provinceId: selectedProvinceId }, function (cities) {
var citiesSelect = $('#SelectedCityId');
citiesSelect.empty();
$.each(cities, function (index, city) {
citiesSelect.append(
$('<option/>')
.attr('value', city.Id)
.text(city.Name)
);
});
});
});
$('#SelectedCityId').change(function () {
var selectedCityId = $(this).val();
$.getJSON('#Url.Action("Suburbs")', { cityId: selectedCityId }, function (suburbs) {
var suburbsSelect = $('#SelectedSuburbId');
suburbsSelect.empty();
$.each(suburbs, function (index, suburb) {
suburbsSelect.append(
$('<option/>')
.attr('value', suburb.Id)
.text(suburb.Name)
);
});
});
});
});
</script>
<div>
Province:
#Html.DropDownListFor(x => x.SelectedProvinceId, new SelectList(Model.Provinceses, "Id", "Name"))
</div>
<div>
City:
#Html.DropDownListFor(x => x.SelectedCityId, Enumerable.Empty<SelectListItem>())
</div>
<div>
Suburb:
#Html.DropDownListFor(x => x.SelectedSuburbId, Enumerable.Empty<SelectListItem>())
</div>
Controller
This is the controller of my project
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using FA_CS.Models.Credit;
namespace FA_CS.Controllers
{
public class HomeController : Controller
{
public ActionResult Spider()
{
var model = new CreditCarModel
{
Provinceses = Enumerable.Range(1, 10).Select(x => new Province
{
Id = (x + 1).ToString(),
Name = "Province" + x
})
};
return View(model);
}
public ActionResult Suburbs(int cityId)
{
var suburbs = Enumerable.Range(1, 5).Select(x => new
{
Id = x,
Name = "suburb" + x
});
return Json(suburbs, JsonRequestBehavior.AllowGet);
}
public ActionResult Cities(int provinceId)
{
var cities = Enumerable.Range(1, 5).Select(x => new
{
Id = x,
Name = "city" + x
});
return Json(cities, JsonRequestBehavior.AllowGet);
}
}
}

You need to call the ajax by $.ajax().
You wrote :
$.getJSON('#Url.Action("Cities")', { provinceId: selectedProvinceId }, function (cities) {
var citiesSelect = $('#SelectedCityId');
citiesSelect.empty();
$.each(cities, function (index, city) {
citiesSelect.append(
$('')
.attr('value', city.Id)
.text(city.Name)
);
});
});
Instead of that you need to code :
var citiesSelect = $('#SelectedCityId');
$.ajax({
url: "/Home/Cities",
type: "GET", //these is must
async: false, //these is optional
cache: false, //these is for IE
contentType: "application/json; charset=utf-8",
dataType: "json",
data: { provinceId: 1 },
success: function (data) {
$('#SelectedSuburbId').html("");
var cities=eval(data);
var citiesHtml = "";
for (i = 0; i < cities.length; i++) {
citiesHtml += '<option value="' + cities[i].Id + '" >' + cities[i].Name + '</option>';
}
$('#SelectedSuburbId').html(citiesHtml);
}
});
You get the return of the json call by "data"

With the above code drop down can be populated.
But for getting the values you need to run a query in top of the “Cities” method.
And return a list of city.
public ActionResult Cities(int provinceId)
{
var cities = Enumerable.Range(1, 5).Select(x => new
{
Id = x,
Name = "city" + x
});
return Json(cities, JsonRequestBehavior.AllowGet);
}
}

Related

Listing Tales in HTML5 using API and Javascipt

I have an sql database with one table called "Tale", which has 2 rows: "ID", "Tale" containing 10 tales. I would like to list them to an HTML page. If I run the html, the result is "Undefined" ten times. Here is the code:
<!DOCTYPE html>
<html>
<head>
<meta charset='utf-8' />
<title>Mesék</title>
<link href="mesekStyle.css" rel="stylesheet" />
</head>
<body>
<p id="cim">Mesék</p>
<form>
<div id='meselist'>
</div>
<div>
<input id='meseText' type='text' placeholder='Ide írd a mesét' />
</div>
<button id='addButton' type='button' >Új mese felvétele</button>
</form>
<script>
document.getElementById('addButton').addEventListener('click', () => {
let data = {
meseText: document.getElementById('meseText').value
}
fetch('api/tales',
{
method: 'POST',
headers: {
'Content-Type': 'application/json'
},
body: JSON.stringify(data)
}
).then(x => {
if (x.ok) {
alert('Siker');
} else {
alert('Kudarc');
}
});
});
function MeseBetöltés() {
fetch('api/tales')
.then(result => {
if (!result.ok) {
console.error(`Hibás letöltés: ${result.status}`);
return null;
} else {
return result.json();
}
})
.then(data => {
for (var i = 0; i < data.length; i++) {
document.getElementById("meselist").innerHTML += data[i].meseText += "<br/>"
}
})
}
window.onload = () => {
MeseBetöltés();
}
</script>
</body>
</html>
Also I tried adding new tales trough the textbox "meseText" and saving it with the button "addButton", and it works, it adds a new column to the SQL table but with the value NULL. Can you please help?
Here is the API Controller:
using HajosTeszt.MeseModels;
using Microsoft.AspNetCore.Mvc;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
// For more information on enabling Web API for empty projects, visit https://go.microsoft.com/fwlink/?LinkID=397860
namespace HajosTeszt.Controllers
{
[Route("api/tales")]
[ApiController]
public class MeseController : ControllerBase
{
// GET: api/<MeseController>
[HttpGet]
public IEnumerable<Tale> Get()
{
MeseContext context = new MeseContext();
return context.Tales.ToList();
}
// GET api/<MeseController>/5
[HttpGet("{id}")]
public Tale Get(int id)
{
MeseContext context = new MeseContext();
var keresettMese = (from x in context.Tales
where x.Id == id
select x).FirstOrDefault();
return keresettMese;
}
// POST api/<MeseController>
[HttpPost]
public void Post([FromBody] Tale újMese)
{
MeseContext context = new MeseContext();
context.Tales.Add(újMese);
context.SaveChanges();
}
// PUT api/<MeseController>/5
[HttpPut("{id}")]
public void Put(int id, [FromBody] string value)
{
}
// DELETE api/<MeseController>/5
[HttpDelete("{id}")]
public void Delete(int id)
{
MeseContext context = new MeseContext();
var törlendőMese = (from x in context.Tales
where x.Id == id
select x).FirstOrDefault();
context.Remove(törlendőMese);
context.SaveChanges();
}
[HttpGet]
[Route("count")]
public int M1()
{
MeseContext context = new MeseContext();
int mesékszáma = context.Tales.Count();
return mesékszáma;
}
}
}
Thank you very much.
Your mistake is in fetching the data
fetch(`{your backend base url}/api/tales`)
Explanation -> If you use /api/tales then the browser will interpret it as {your frontend base url}/api/tales therefore you need to specify the base URL, ie, {your backend base url}/api/tales

View doesn't show updated data after POST action

I'm trying to load a partial view and change it through a POST Ajax, but model doesn't update on view.
This is how I'm loading my partial:
#{
Html.RenderAction("UltimeNovità", "User");
}
and my action in UserController is:
public ActionResult UltimeNovità()
{
_UltimeNovitàViewModel model = new _UltimeNovitàViewModel();
model.NumeroPagina = 1;
return PartialView("~/Views/User/Partial/_UltimeNovità.cshtml",model);
}
and here the partial:
#model Mine.Models._UltimeNovitàViewModel
<script>
$(document).ready(function () {
});
function nextPage() {
$.ajax({
url: '#Url.Action("UltimeNovitàPaginaSuccessiva")',
type: 'POST',
data: { pagina: #Model.NumeroPagina },
success: function (data) {
$('#x').text('#Model.NumeroPagina');
},
error: function (xhr) {
alert('error');
}
});
}
</script>
<p id="x">1</p>
finally, the POST action in the same controller:
[HttpPost]
public ActionResult UltimeNovitàPaginaSuccessiva(int pagina)
{
_UltimeNovitàViewModel model = new _UltimeNovitàViewModel();
ModelState.Clear();
model.NumeroPagina = pagina + 1;
model.UltimeNovità = UserControllerMethods.GetUltimeNovità(model.NumeroPagina);
return PartialView("~/Views/User/Partial/_UltimeNovità.cshtml", model);
}
My problem is: why after the POST action #Model.NumeroPagina is always 1? I expect that each time I press the button which calls the function with ajax the #Model.NumeroPagina increases by 1 and it's shown in my paragraph.
The button is in the main page that contains the partial, actions are always hit and during debugging I can see that model.NumeroPagina is 2, but in view is always 1.
There are some issues in your code. I don't see where you're updating the HTML content, also you're generating the nextPage function eachTime, and others.
Check this sample, it should be easy to use.
Controller/ViewModel
public class NovitàController : Controller
{
public ActionResult Index()
{
return View();
}
public ActionResult UltimeNovità(int? page)
{
var model = new UltimeNovitàViewModel
{
NumeroPagina = 1
};
return PartialView("_UltimeNovità", model);
}
[HttpPost]
public ActionResult UltimeNovitàPaginaSuccessiva(int pagina)
{
var model = new UltimeNovitàViewModel
{
NumeroPagina = pagina + 1,
UltimeNovità = GetUltimeNovità(pagina + 1)
};
return PartialView("_UltimeNovità", model);
}
public string GetUltimeNovità(int page)
{
return $"Ultime Novità: {page}"; //FOR DEMO
}
public class UltimeNovitàViewModel
{
public int NumeroPagina { get; set; }
public string UltimeNovità { get; set; }
}
}
_UltimeNovità partial view:
#model NovitàController.UltimeNovitàViewModel
#if (Model.UltimeNovità != null)
{
<div>
UltimeNovità: #Model.UltimeNovità
</div>
}
<div>
Pagina: #Model.NumeroPagina
</div>
<div>
<a class="next-page-link" href="#Url.Action("UltimeNovitàPaginaSuccessiva", "Novità", new {pagina = Model.NumeroPagina})">
Pagina Successiva
</a>
</div>
And the Index page:
#{
ViewBag.Title = "Novità";
}
<div id="RootDiv">
#{ Html.RenderAction("UltimeNovità", "Novità");}
</div>
#section scripts{
<script>
$(function() {
function bindNextPageLink() {
$("#RootDiv a.next-page-link").click(function(event) {
event.preventDefault();
$.post($(this).attr("href"),
function(data) {
$("#RootDiv").html(data);
bindNextPageLink();
}
);
});
}
bindNextPageLink();
});
</script>
}
I tried to write the example very similar to your code.

how to pass a knockout model to jsonresult parameter

I was trying to pass a whole object to the jsonresult method. but there are errors that occur. It might be the way I bound it but I'm not sure. I'm new to JS and KOJS. Once the Login button, which is bound to the LogUser method, is clicked, it should call the Authenticate(Employee p) method.
here is my class model
public class Employee
{
[Key]
public long AutoId { get; set; }
[Required]
Display(Name = "Employee ID")]
public string EmployeeId { get; set; }
[Required]
[DataType(DataType.Password)]
[Display(Name = "Password")]
public string EmployeePassword { get; set; }
public string FirstName { get; set; }
public string LastName { get; set; }
public string MiddleName { get; set; }
}
this is my knockoutjs view model
$(function () {
ko.applyBindings(LoginVm);
});
//VIEW MODEL. MODEL IS BELOW THIS
var LoginVm = {
thisEmp: ko.observable(EmpObject),
LogUser: function () {
var self = this;
//trying to check if thisEmp properties has values by alerting
alert("ID: " + thisEmp.EmployeeId() + " Password: " + thisEmp.EmployeePassword());
$.ajax({
url: '/Employee/AuthenticateUser',
type: 'POST',
dataType: 'json',
data: ko.toJSON(thisEmp),
contentType: 'application/json',
success: function (errorMsg) {
if (errorMsg === '') {
}
}
});
}
};
//MODEL
var EmpObject = {
EmployeeId: ko.observable(''),
EmployeePassword: ko.observable('')
}
this is my view and how I bound the properties
#using (Html.BeginForm()) {
#Html.ValidationSummary(true)
<fieldset>
<legend>Employee</legend>
<div class="editor-label">
#Html.LabelFor(model => model.EmployeeId)
</div>
<div class="editor-field">
#Html.TextBoxFor(model => model.EmployeeId, new { data_bind="value: thisEmp.EmployeeId()"})
#Html.ValidationMessageFor(model => model.EmployeeId)
</div>
<div class="editor-label">
#Html.LabelFor(model => model.EmployeePassword)
</div>
<div class="editor-field">
#Html.PasswordFor(model => model.EmployeePassword, new { data_bind="value: thisEmp.EmployeePassword()"})
#Html.ValidationMessageFor(model => model.EmployeePassword)
</div>B
<p>
#*<input type="submit" value="Create"/>*#
<input type="button" value="Login" data-bind="click: LogUser"/>
</p>
</fieldset>
}
this is the error
Uncaught TypeError: Unable to process binding "value: function (){return thisEmp().EmployeeId }"
Message: Cannot read property 'EmployeeId' of undefined
at value (eval at createBindingsStringEvaluator
The error is being thrown because you have defined LoginVm beforeEmpObject. You need to change the order they are declared.
Are you sure this is the code that produced this error? In your view you're binding thisEmp.EmployeeId() but th error says it's unable to bind thisEmp().EmployeeId. I think you tried both of them and the error still persisted. Either way, there is no need to make thisEmp an observable. It's enough that the properties are observables.
So, change your code to:
$(function () {
ko.applyBindings(new LoginVm());
});
//MODEL
var EmpObject = {
EmployeeId: ko.observable(''),
EmployeePassword: ko.observable('')
}
//VIEW MODEL. MODEL IS BELOW THIS
var LoginVm = function() {
var self = this;
self.thisEmp = EmpObject;
self.LogUser = function () {
var self = this;
//trying to check if thisEmp properties has values by alerting
alert("ID: " + self.thisEmp.EmployeeId() + " Password: " + self.thisEmp.EmployeePassword());
$.ajax({
url: '/Employee/AuthenticateUser',
type: 'POST',
dataType: 'json',
data: ko.toJSON(self.thisEmp),
contentType: 'application/json',
success: function (errorMsg) {
if (errorMsg === '') {
}
}
});
}
};
And change the bindings in view to:
#Html.TextBoxFor(model => model.EmployeeId, new { data_bind="value: thisEmp.EmployeeId"})
#Html.PasswordFor(model => model.EmployeePassword, new { data_bind="value: thisEmp.EmployeePassword"})

Filtering datatable with dropdown select

I am trying to filter datatable by select.
I can see the data in select but don't know how to filter it.
Here's my code.
Thanks
function getSearchList() {
$.post('#(Url.Action("GetSearchList", "ESR"))')
.success(function (data) {
if (data.length > 0) {
$.each(data, function () {
$('#Search_Id').append($('<option>', {
value: this.ID,
text: this.S_ID
}));
});
}
$(window).unblock();
})
}
and
$(document).ready(function () {
$('#Search_Id').select2({
placeholder: "Search",
allowClear: true,
});
});
and
<div class="col-sm-2">
<select class="select" id="Search_Id"></select>
</div>
following are whole backend side of codes
following are whole backend side of codes
following are whole backend side of codes
following are whole backend side of codes
following are whole backend side of codes
following are whole backend side of codes
public List<SearchId> GetSearchIdData()
{
string strSQL = string.Format(#"SELECT ID, S_ID FROM TBR");
using (var conn = SqlUtility.GetDBConnection())
{
conn.Open();
return conn.Query<SearchId>(strSQL).ToList();
}
}
and
public ActionResult GetSearchIdList()
{
JsonResult result;
List<SearchId> List = service.GetSearchIdList();
result = Json(List);
result.MaxJsonLength = int.MaxValue;
return result;
}
and
public class SearchId
{
public int ID { get; set; }
public string S_ID{ get; set; }
}
and
public List<SearchId> GetSearchIdList()
{
return repo.GetSearchIdData();
}

How to popup alert when TextBoxFor's input does not exist in database?

NPG_Chemical_Measurement_Methods is an ICollection type. In my Chemical.cshtml, I have:
<div id="nioshs">
#Html.EditorFor(model => model.NPG_Chemical_Measurement_Methods)
</div>
and in the EditorTemplate view:
<div class="method" style="display:inline-block;">
<p>
#Html.RemoveLink("x", "div.method", "input.mark-for-delete")
#Html.HiddenFor(x => x.DeleteMethod, new { #class = "mark-for-delete" })
#Html.TextBoxFor(x => x.Measurement_Method)
#Html.ValidationMessageFor(model => model.Measurement_Method, "", new { #class = "text-danger" })
#Html.Hidden("Measurement_Type", "NIOSH")
</p>
</div>
I want to have something like when I give input for #Html.TextBoxFor(x => x.Measurement_Method), then click on other place of the current page, an alert will popup says Not exist in Database if record cannot be found in Measurement_Method table.
NPG_Chemical.cs has:
public partial class NPG_Chemical
{
public NPG_Chemical()
{
this.NPG_Chemical_Measurement_Methods = new HashSet<NPG_Chemical_Measurement_Method>();
}
[StringLength(256)]
[Remote("IsUserExists", "NPG_Chemical", ErrorMessage = "Chemical Name already in use")]
public string Chemical { get; set; }
public virtual ICollection<NPG_Chemical_Measurement_Method> NPG_Chemical_Measurement_Methods { get; set; }
internal void CreateMeasurementMethods(int count = 1)
{
for (int i = 0; i < count; i++)
{
NPG_Chemical_Measurement_Methods.Add(new NPG_Chemical_Measurement_Method());
}
}
Measurement_Method.cs has:
public partial class NPG_Chemical_Measurement_Method
{
[StringLength(256)]
[Remote("IsNIOSHExists", "NPG_Chemical", ErrorMessage = "NIOSH number does not exist")]
public string Measurement_Method { get; set; }
}
NPG_ChemicalController has:
public JsonResult IsUserExists(string Chemical)
{
return Json(!db.NPG_Chemical.Any(x => x.Chemical == Chemical), JsonRequestBehavior.AllowGet);
}
public JsonResult IsNIOSHExists(string Measurement_Method)
{
System.Diagnostics.Debug.WriteLine("value:",Measurement_Method);
return Json(db.NPG_NIOSH_Method.Any(x => x.Measurement_Number == Measurement_Method), JsonRequestBehavior.AllowGet);
}
This hopefully will get you close. I'm just writing this from memory. But basically one way to do this is handle an onblur event of your textbox with a javascript function. Then do an ajax call to a controller sending the value of Measurement_Method, validate the data and return true or false. If false show an alert box. You'll need to include the jquery library to use this.
#Html.TextBoxFor(x => x.Measurement_Method, new {onblur = "Validate()"})
Then javascript
function Validate() {
$.ajax({
url: "#Url.Action("CheckTextField", "Controller")\?value=" + $('#Measurement_Method').val(),
dataType: "html",
success: function(data) {
if (data == "false")
{
alert('Not exist in Database');
}); }
Your controller
public string CheckTextField(string value)
{
//validate the value here
return "true" or "false"
}

Categories

Resources