Listing Tales in HTML5 using API and Javascipt - javascript

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

Related

ajax post to MVC controller failed with 400 Bad Request

I ajax post a complex object to a .Net 5.0 controller (not a WebAPI controller). The declaration of the MVC controller and TypeScript are as below. The [HttpPost] Edit action is invoked if I post with <input type='submit' value='Save' />. However, the controller's action is not invoked at all if I post through jQuery .ajax(). The browser console says "POST https://localhost:44381/Question/Edit 400 (Bad Request)". I read many code samples and nothing indicates anything wrong with the code. Does anyone know why?
namespace theProject.Controllers {
public class BaseController: Controller {
protected BaseController(IConfiguration configuration, ILogger logger) {
.......(elided
for brevity)
}
}
}
namespace theProject.Controllers {
//ToDo: [Authorize]
public class QuestionController: BaseController {
public QuestionController(IConfiguration configuration, ILogger < QuestionController > logger): base(configuration, logger) {}
[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult Edit([FromBody] PostbackModel model) {
if (ModelState.IsValid) {
List < UserAnswer > newAnswers = model.NewAnswers;
List < UserAnswer > oldAnswers = model.OldAnswers;
List < UserAnswer > updatedAnswers = model.UpdatedAnswers;
UserAnswer thisAnswer = new();
if (newAnswers != null)
thisAnswer = newAnswers.Find(x => x.StageName != string.Empty);
else if (oldAnswers != null)
thisAnswer = oldAnswers.Find(x => x.StageName != string.Empty);
else if (updatedAnswers != null)
thisAnswer = updatedAnswers.Find(x => x.StageName != string.Empty);
//ToDo: call webapi Question controller to persist the data to database
return RedirectToAction(nameof(Edit), new {
stage = thisAnswer.StageName, personName = thisAnswer.personName, custID = thisAnswer.custID.ToString(), redirectFrom = "Edit"
});
} else {
return RedirectToAction("Index", "Home");
}
}
let postBackModel: AjaxPostbackModel = < AjaxPostbackModel > {};
postBackModel.NewAnswers = newAnswers
postBackModel.OldAnswers = oldAnswers;
postBackModel.UpdatedAnswers = updatedAnswers;
let thisUrl: string = $('form').prop('action');
$.ajax({
type: "POST",
url: thisUrl,
data: JSON.stringify(postBackModel),
contentType: 'application/json; charset=utf-8',
}).done(function(result) {
$('.spinnerContainer').hide();
console.log('postback result', result.message);
console.log('inserted entities', result.insetedEntities);
dialogOptions.title = 'Success';
$('#dialog')
.text('Data is saved. ' + result.message)
.dialog(dialogOptions);
}).fail(function(error) {
console.log('postback error', error);
$('.spinnerContainer').hide();
dialogOptions.title = error.statusText;
dialogOptions.classes = {
'ui-dialog': 'my-dialog',
'ui-dialog-titlebar': 'my-dialog-header'
}
$('#dialog')
.text('Data is not saved')
.dialog(dialogOptions)
});
Since you use [ValidateAntiForgeryToken] in action,you need to add the following code to your ajax to add antoforgery token to header.
headers: { "RequestVerificationToken": $('input[name="__RequestVerificationToken"]').val() },

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 pass Dictionary from c#(server) to javascript(client)

I have a function in c# that builds dictionary ,I need to pass this dictionary to my java-script function.
This is what I have tried
My server function
public partial class login : System.Web.UI.Page
{
protected Dictionary<string, string> GetTradingTypeToSelect()
{
Dictionary<string, string> dict = new Dictionary<string, string>();
try {
string Types =GetString("some text);
var items = Types.Split(new[] { ';' }, StringSplitOptions.RemoveEmptyEntries)
.Select(s => s.Split(new[] { '=' }));
foreach (var item in items)
{
dict.Add(item[1], item[0]);
}
//this working 100%
}
catch (Exception ex)
{
}
return dict;
}
}
My client:
$(document).ready(function () {
$("#Account").keyup(function () {
var TradingTypeToSelect = '<%=GetTradingTypeToSelect();%>';
//TradingTypeToSelect is equals to string '<%=GetTradingTypeToSelect();%>'
var test = TradingTypeToSelect[0].key;
var test2 = TradingTypeToSelect[0].value;
});
});
What am I missing here?
You can create a [WebMethod] in the code behind and call it from javascript using $.ajax.Below is a complete example:
Code behind:
[System.Web.Services.WebMethod]
public static Dictionary<string, string> GetTradingTypeToSelect()
{
var dict = new Dictionary<string, string>();
dict.Add("1", "Item 1");
dict.Add("2", "Item 2");
return dict;
}
.ASPX:
<head runat="server">
<title></title>
<script src="//code.jquery.com/jquery-1.12.3.min.js"></script>
<script type="text/javascript">
$(function () {
$("#Account").keyup(function () {
$.ajax({
type: "POST",
url: "AjaxCallExample.aspx/GetTradingTypeToSelect",
contentType: "application/json;charset=utf-8",
success: function (data) {
alert(data.d["1"]);
alert(data.d["2"]);
},
error: function (errordata) {
console.log(errordata);
}
});
});
});
</script>
</head>
<body>
<form id="form1" runat="server">
<input id="Account" type="text" />
</form>
</body>
How about exposing the dictionary in the view model:
public Dictionary<string, string> TradingTypesToSelect { get; set; }
And iterate over the dictionary inside the <script> block, creating a JavaScript associative array, like so:
<script>
var tradingTypesToSelect = {};
<% foreach (var tradingType in Model.TradingTypesToSelect) { %>
tradingTypesToSelect["<%= tradingType.Key %>"] = "<%= tradingType.Value %>";
<% } %>
</script>
At least this way you don't have to make another call (via AJAX) to retrieve additional data.
I believe you need to make a WebMethod to enable the server function to be called from the client side. Here is an example:
Calling ASP.Net WebMethod using jQuery AJAX

ASP.Net MVC Scripts not working with controller's default action url. Same is working with controller/action url

When mvc application is queried with controller name alone in the url without specifying action, the page is rendered but ajax/scripts are not working, whereas the same page when queried with action in the url, is working as expected.
Not working url: http://localhost:port/Search --> Page rendering is fine but scripts are not working - Search results are not showing up
Working url: http://localhost:port/Search/Index --> Page and scripts are working as expected - Search results are showing up
C#:
public class SearchController : Controller
{
private readonly List<string> _cars;
public SearchController()
{
_cars = new List<string>{"Corolla","Camry","Civic","Land Rover","Range Rover","Polo"};
}
public ActionResult Index()
{
return View();
}
public async Task<JsonResult> GetMatchingResults(string filter)
{
var results = await Task.Run(() => GetSearchResults(filter));
return new JsonResult() { Data = results,JsonRequestBehavior = JsonRequestBehavior.AllowGet };
}
private List<string> GetSearchResults(string filter)
{
var results = _cars.Where(car => car.Contains(filter));
return results.ToList();
}
}
HTML:
<html>
<head>
#using System.Web.Optimization
#Scripts.Render("~/bundles/jquery")
#Scripts.Render("~/bundles/bootstrap")
<meta name="viewport" content="width=device-width" />
<script src="~/Scripts/ApplicationScripts/SearchViewJS.js" type="text/javascript"></script>
<title>SearchView</title>
</head>
<body>
<div>
<input class="searchText" type="search" />
</div>
<div>
<input class="searchResults" type="text" />
</div>
</body>
</html>
JS:
$(document).ready(function () {
$(".searchText").on('input', function (event) {
var filter = $(event.currentTarget).val();
search(filter).then(display);
});
function search(filter) {
return $.getJSON('GetMatchingResults/', { 'filter': filter });
}
function display(result) {
$(".searchResults").val(result);
}
})
It is because of the context of
$.getJSON('GetMatchingResults/', { 'filter': filter });
In the first case that will be trying to hit /GetMatchingResults the second tries to hit /search/GetMatchingResults. A fix could be to use
$.getJSON('/search/GetMatchingResults/', { 'filter': filter });
Or even better would be to generate the path from a HTML helper that will route correctly if you update your routing rules. This would look something like
$.getJSON('#Url.Action("GetMatchingResults", "Search")', { 'filter': filter });

Why Javascript is not firing? [closed]

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);
}
}

Categories

Resources