JS+ASP Net Core Get data from controller - javascript

the question arose: How to get data from the controller in asp net core using js?
I tried to send a post request head-on, but it seems to me there is a more elegant solution
At the same time, I need this to happen when the html of the Select element changes
I wrote a script that changes the field when the select changes
function Change_Aud() {
var x = document.getElementById("Levelid").value;
document.getElementById("Hardware_La").value = x ;
}
Controller example
public async Task<IActionResult> Get_Hardware_Unit(int id)
{
Level level = _context.Levels.Where(p => p.Number == id.ToString()).First();
return Content(level.Public_Hardware.ToString());
}

Test page code in cshtml:
#{
ViewData["Title"] = "Home Page";
int count = 5;
}
<script src="https://code.jquery.com/jquery-2.2.4.js" integrity="sha256-iT6Q9iMJYuQiMWNd9lDyBUStIq/8PuOW33aOqmvFpqI=" crossorigin="anonymous"></script>
<script>
function myFunction(selectObject) {
var value = selectObject.value;
$("#selectnum").html(value);
backendfunc(value);
}
function backendfunc(value) {
$.ajax({
url: "/Test/Get_Hardware_Unit",
type: "GET",
data: { id: value },
success: function (res) {
$("#convertnum").html(res);
},
error: function (hata, ajaxoptions, throwerror) {
$("#convertnum").html("convert failed");
}
});
}
</script>
<div>
<select name="num" id="num-select" onchange="myFunction(this)">
<option value="">--Please choose an option--</option>
<option value="1">One</option>
<option value="2">Two</option>
<option value="3">Three</option>
</select>
</div>
<br />
<br />
<div>
You select value is : <span id="selectnum"></span>
</div>
<br />
<br />
<div>
After backend converted, here is : <span id="convertnum"></span>
</div>
My function in Controller:
public async Task<IActionResult> Get_Hardware_Unit(int id) {
string result = string.Empty;
if (id == 1) {
result = "①";
}
if (id == 2)
{
result = "②";
}
if (id == 3)
{
result = "③";
}
return Content(result);
}
Test Result

Related

C# AJAX reloading the form

I'm learning C# MVC and now creating a project.
I have a problem with understanding AJAX - I can't understand why it doesn't work. After clicking the save button the form is reloading (?). After the second click, the code goes to SearchRouts(). But then - just nothing happens. Neither code from success, nor from error block (I set simple alerts to check it). It looks like the form just reloads (?). I can't figure out what's happening.
I think it is something with the end of SearchRoutes() - should I send the response in another way?
Thank you for your help.
Here is my code:
Index.cs.html:
<form id="search_form" method="post">
<label class="search__header">Długość: </label></br>
<div class="search__options">
<select class="search__select" name="search_len" id="search_len" multiple>
<option value="len1">0-100 km</option>
<option value="len2">100-150 km</option>
<option value="len3">150-300 km</option>
<option value="len4">+300 km</option>
</select>
</div>
<label class="search__header">Difficulty: </label></br>
<div class="search__options">
<select class="search__select" name="search_dif" id="search_dif" multiple>
<option value="easy">Easy</option>
<option value="medium">Medium</option>
<option value="hard">Hard</option>
</select>
</div>
<label class="search__header">Pavement: </label></br>
<div class="search__options">
<select class="search__select" name="search_pav" id="search_pav" multiple>
<option value="asphalt">Asphalt</option>
<option value="forest">Forest</option>
<option value="mix">Mix</option>
</select>
</div>
<div class="search_options search__options--submit">
<img class="search__img" src="img/compass.png">
<button class="panel__button panel__button--submit" id="search_submit" type="submit">Search</button>
</div>
</form>
search.js:
$("#search_submit").on("click", function () {
console.log("SUBMIT CLICKED!");
var search_obj = {}
search_obj.Length = $("#search_len").val()[0];
search_obj.Difficulty = $('#search_dif').val()[0];
search_obj.Pavement = $('#search_pav').val()[0];
console.log(search_obj);
alert("ALERT!");
$.ajax({
type: "POST",
url: '/User/SearchRoutes',
data: JSON.stringify(search_obj),
dataType: "json",
contentType: "application/json; charset=utf-8",
success: function (response) {
alert("Success!");
console.log(response);
},
error: function (response) {
alert("Error. Try again.");
}
});
});
UserController.cs:
public ActionResult SearchRoutes([FromBody] JsonSearch search)
{
double min = 0;
double max = 1000;
if(search.Length=="len1")
{
max = 100;
}
else if(search.Length=="len2") {
min = 100;
max = 150;
}
else if(search.Length=="len3")
{
min = 150;
max = 300;
}
else
{
min = 300;
}
var list = _userService.FindRoutes(min, max, search.Difficulty, search.Pavement); // returns C# list of routes objects from database
var json = JsonSerializer.Serialize(list);
return Json(json);
}
In the javascript function call use
$("#search_submit").on("click", function (e) {
console.log("SUBMIT CLICKED!");
e.preventDefault();
...
To skip the reload event after submit is pressed.

pass dropdown list value from view to controller and resend The same view in asp.net core 3.1?

View :
<select id="count" name="count" class="form-control">
<option value="0">Choose</option>
<option value="2">two</option>
<option value="3">three</option>
<option value="4">four</option>
<option value="5">five</option>
</select>
Jquery:
<script>
$("#count").change(function () {
let count = $("#count :selected").val();
if (count != 0) {
$.getJSON("/AdminPanel/Poll/Create/" + count);
}
});
</script>
Controller :
public IActionResult Create(int id)
{
ViewBag.Count = id;
return View();
}
How can Send Value As Viewbag to View From Controller?
I want use in loop... in razor page
You can't. What I'd recommend is having a separate action method:
public IActionResult Create(int id)
{
return Json(new { count = id });
}
And then in the GET request:
$("#count").change(function () {
let count = $("#count :selected").val();
if (count != 0) {
$.getJSON("/AdminPanel/Poll/Create/" + count, function(d) {
$("#count").val(d.count);
});
}
});
It's essentially syncing the two results by updating the server and refreshing the UI on the client. ViewBag is not recognized in the JavaScript callback, but you can return whatever you want and then make the update in JS. You can return a PartialView to replace part of the HTML page, for instance.

How to get selected value from dropdownlist in database in asp.net mvc?

I am trying to get (agent_name&slot_name) from tb_agent & tb_parkingslot (ie. selected from 2 dropdownlist) to tb_freeslot.Not getting the selected values in tb_freeslot instead getting the 2 id's of agent_name&slot_name.what i need to have these selected values in prescribed db table.
Controller
public ActionResult Addagentslot1(FormCollection collection)
{
try
{
tb_freeslot Addgentslot = new tb_freeslot();
Addgentslot.slotinfree_name = collection["s"].ToString();
Addgentslot.agentinfree_name = collection["a"].ToString();
db.tb_freeslot.Add(Addgentslot);
int j = db.SaveChanges();
if (j > 0)
{
ViewBag.s = "success";
return View();
}
else
{
ViewBag.f = "failed";
return View();
}
catch
{
return View();
}
}
View
#{
safespot1.Models.SafespotEntities db = new safespot1.Models.SafespotEntities();
var getag = db.tb_agent.ToList();
var getsl = db.tb_parkingslots.ToList();
}
<form action="/Admin/Addagentslot1" method="post">
<select name="a">
#foreach(var item in getag)
{
<option value="#item.agent_id">#item.agent_name
</option>
}</select>
<select name="s">
#foreach (var item in getsl)
{
<option value="#item.slot_id">#item.slot_name
</option>
}</select>
<input type="submit" value="add space" />
<div>
<label class="label-success">
#ViewBag.s
</label>
<label class="label-danger">
#ViewBag.f
</label>
</div>
</form>

Get selected value from a dropdown to use it in another dropdown Laravel

In my view, I have two dropdowns, the first dropdown have items and the second dropdown don't have item. It looks like this:
<form action="http://localhost/AutoFill/public/handle-form" method="POST">
<div>
City:<br>
<select name="city">
<option value="">Choose Place</option>
<option value="0">HCM</option>
<option value="1">HN</option>
</select>
</div>
<br>
<div>
Ward:<br>
<select name="ward">
<option value="">---</option>
</select>
</div>
<br>
</form>
Now I want to get the value of the first dropdown to fill data into the second dropdown. I create a function in my controller for returned second dropdown data:
public function getSecondEnumData(Request $request)
{
$firstEnumSelected = $request->city;
$client = new Client();
if ($firstEnumSelected === 0) {
$enumValueResponse = $client->request('GET', 'https://api.myjson.com/bins/zcyj2');
} else {
$enumValueResponse = $client->request('GET', 'https://api.myjson.com/bins/1bx7e6');
}
return json_decode($enumValueResponse->getBody(), true);
}
I searched some post in here, and I think I should write some JavaScript code in my view to do this but I'm not familiar with it so can you help me?
Route
Route::get('/', 'RestController#getFirstEnumData');
You can try like this, My Answer will not give you 100% soluton of your problem as I am little bit confused about your controller function. But I hope it will help you.
First of all your route need to be POST as you are taking Request data in the function.
Route::POST('getFirstEnumData', 'RestController#getSecondEnumData');
add csrf in the meta
<meta name="csrf-token" content="{{ csrf_token() }}" />
And then
<form action="http://localhost/AutoFill/public/handle-form" method="POST">
<div>
City:<br>
<select name="city" id="city">
<option value="">Choose Place</option>
<option value="0">HCM</option>
<option value="1">HN</option>
</select>
</div>
<br>
<div>
Ward:<br>
<select name="ward" id="ward">
<option value="">---</option>
</select>
</div>
<br>
</form>
$("#city").change(function() {
var CSRF_TOKEN = $('meta[name="csrf-token"]').attr('content');
var city = $( "#city" ).val();
$.ajax({ //create an ajax request to get tour list
type: "POST",
url: "/getFirstEnumData",
data : ({
_token: CSRF_TOKEN,
city : city
}),
success: function(response){
var responseData = JSON.parse(response);
var dataLength = responseData.length;
$("#ward").empty();
$("#ward").append("<option value=''>Select</option>");
for( var i = 0; i< dataLength; i++){
var id = responseData[i].id;
var name = responseData[i].name;
$("#ward").append("<option value='"+id+"'>" + name + "(" + name+")"+"
</option>");
}
}
});
});
Place the following code just above your </body> tag, change the success according to your reponse data, also url according to your url
<script>
let origin = document.querySelector(select[name='city'])
let target = document.querySelector(select[name='ward'])
origin.addEventListener('change', function(){
$.ajax({
url: '{{ url('/') }}',
method: 'POST',
data:{ city: origin.value, _token: '{{ csrf_token() }}' },
success: function(response){
response.forEach((opt) => {
target.innerHTML += `<option value=${opt.id}>${opt.value}</option>` //this varies according to your response data
})
}
})
})
</script>

Bootstrap Dual Listbox problems while populate via JavaScript

I have some problem while using Bootstrap Dual Listbox (http://www.virtuosoft.eu/code/bootstrap-duallistbox/). It is not working as expected when the ListBox is populated via java Script.What I mean with not working is the list is not populated properly and the transferring selected items from both list box is not as what as it should work. Somehow when the list is populated by hard coded, it is working well.
This is the part where everything working fine :
<div class="row-fluid">
<div class="container">
<select multiple="multiple" size="10" name="SelectItem" class="eItems" id="SelectItem">
<option value="option1">Option 1</option>
<option value="option2">Option 2</option>
<option value="option3" selected="selected">Option 3</option>
<option value="option4">Option 4</option>
<option value="option5">Option 5</option>
<option value="option6" selected="selected">Option 6</option>
<option value="option7">Option 7</option>
<option value="option8">Option 8</option>
</select>
<script type="text/javascript">
var demo2 = $('.eItems').bootstrapDualListbox({
nonselectedlistlabel: 'Non-selected',
selectedlistlabel: 'Selected',
preserveselectiononmove: 'moved',
moveonselect: false,
bootstrap2compatible : true
});
</script>
</div>
</div>
but when populate using JavaScript, it is populated but the functions is not functioning well :
The data collector from Controller :
<script type="text/javascript">
function ProductChange() {
$.getJSON("/WEBAPP/MasterData/GetItems", null, function (data) {
var items;
$.each(data, function (i, item) {
items += "<option value=" + item.Value + ">" + item.Key + "</option>";
});
$("#SelectItem").html(items);
})
}
</script>
The list box populating here :
<div class="row-fluid">
<div class="row-fluid">
<div class="container">
<select id="SelectProduct"></select>
</div>
</div>
<div class="row-fluid">
<div class="container">
<select multiple="multiple" size="10" name="SelectItem" class="eItems" id="SelectItem"></select>
<script type="text/javascript">
var demo2 = $('.eItems').bootstrapDualListbox({
nonselectedlistlabel: 'Non-selected',
selectedlistlabel: 'Selected',
preserveselectiononmove: 'moved',
moveonselect: false,
bootstrap2compatible : true
});
$(function () {
$("#SelectProduct").change(function () {
ProductChange();
});
});
</script>
</div>
</div>
</div>
The controller :
[HttpGet]
public JsonResult GetItems(int productID = 0)
{
try
{
var items =
from item in dbItem.items.ToList()
join p in dbItem.Productitems.ToList()
on item.itemID equals p.itemID
where item.Language.LanguageCode.Trim() == repLanguage
where p.ProductID == productID
orderby item.DisplaySequence
select new { Key = item.itemDescription, Value = item.itemID };
if (items.Count() == 0)
{
items = from item in dbItem.items.ToList()
where item.Language.LanguageCode.Trim() == repLanguage
orderby item.DisplaySequence
select new { Key = item.itemDescription, Value = item.itemID };
}
return Json(items, JsonRequestBehavior.AllowGet);
}
catch (Exception ex)
{
return Json(new { Result = "ERROR", Message = ex.Message });
}
}
Is it because the java script is reloaded every time the trigger action takes place?
Apologize if the explanation is not so clear and just let me know if u need more information.
Thanks a lot
I cannot populate the list box properly by calling and a populate function directly as normal drop down. I changed the populate code as below
<select multiple="multiple" size="10" name="SelectItem" class="eItems" id="SelectItem"></select>
<script type="text/javascript">
var demo2 = $('.eItems').bootstrapDualListbox({
nonselectedlistlabel: 'Non-selected',
selectedlistlabel: 'Selected',
preserveselectiononmove: 'moved',
moveonselect: false,
bootstrap2compatible: true
});
$(function () {
$("#SelectProduct").change(function () {
$('#SelectItem').empty();
demo2.trigger('bootstrapduallistbox.refresh');
$.getJSON("/WEBAPP/MasterData/GetItems", { productID: $("#SelectProduct").val() }, function (data) {
var items;
$.each(data, function (i, item) {
demo2.append("<option value=" + item.Value + ">" + item.Key + "</option>");
});
demo2.trigger('bootstrapduallistbox.refresh');
})
});
});
</script>
From my understanding, the list items are re-populate using original code. Correct me if I am wrong.
You should try something like this:
demo2.trigger('bootstrapDualListbox.refresh' , true);
This works form me!
For me, bootstrapDualListbox is case sensitive - bootstrapduallistbox did not work. I wanted to post this in case any body else has this issue.

Categories

Resources