How to pass Multiple input array element values - javascript

As you can see I have a for loop with Multiple ID and I want get the value of IDs and pass them to my controller, how can I achieve this ?
<form id="UserEdit">
#for (int i = 0; i < Model.Rights.Count; i++)
{
#Html.HiddenFor(m => m.Rights[i].ID)
}
<input id="BtnEditUserJS" onclick="PostFormUserEdit();" type="submit" value="Edit">
</form>
Generated HTML:
<input id="Rights_0__ID" name="Rights[0].ID" type="hidden" value="31">
<input id="Rights_1__ID" name="Rights[1].ID" type="hidden" value="32">
JavaScript:
function PostFormUserEdit() {
$.ajax({
type: 'POST',
url: '#Url.Action("EditUser")',
dataType: 'json',
data: ,
success: function (run) {
console.log('Ok');
},
error: function () {
console.log('something went wrong - debug it!');
}
});
}
Controller:
[HttpPost]
public JsonResult EditUser(int[] RightId)
{
var rights = db.Rights.Where(b => RightId.Contains(b.Id)).ToList();
//do something with rights
}

You can achieve it this way :
function PostFormUserEdit()
{
var arr = [];
$("#UserEdit input[type='hidden']").each(function (index, obj) {
arr.push(obj.val());
});
$.ajax({
type: 'POST',
url: '#Url.Action("EditUser")',
dataType: 'json',
data: arr , // or you can try data: JSON.stringify(arr)
success: function (run) {
console.log('Ok');
},
error: function () {
console.log('something went wrong - debug it!');
}
});
}

Related

In ASP.NET Razor Page Jquery Ajax Function not Working

I have a two onchange function for a page called create delivery request. One is when the dropdownlist of receiver changes, then it should show the phone number & address of receiver selected. Another one is when the dropdownlist of delivery item changes, then it should set the max attribute for the quantity.
The url of both these are linked to the customized OnGet method in razor page.
However, usually the above Onget method is hit but the below one is not. And the above OnGet method can't get the dryfood with the passed ID as well, it is null inside. And the two jQuery ajax function doesn't work at all. I'm totally a beginner. Hope that there is someone who can help me. Thanks in advance.
In create.cshtml:
<div class="mb-3">
Receiver Name
<select id="receiver" asp-for="Delivery.ReceiverID" asp-items="Model.ReceiverList" class="form-control">
<option>--Select the Receiever--</option>
</select>
</div>
<div class="mb-3">
Receiver Phone
<span id="receiverphone" class="form-control">----</span>
</div>
<div class="mb-3">
Receiver Address
<div id="receiveradrs1" class="form-control">----</div>
<div id="receiveradrs2" class="form-control">----</div>
</div>
<div class="mb-3">
Delivery Item
<select id="deliveryitem" asp-for="DeliveryItem.DryFoodID" asp-items="Model.DeliveryItemList" class="form-control">
<option>--Select Delivery Item--</option>
</select>
</div>
<div class="mb-3">
Quantity
<input id="quantity" asp-for="DeliveryItem.Quantity" min="1" class="form-control" />
</div>
In create.csthml.cs, two customized OnGet method here:
public async Task<IActionResult> OnGetSetMaxQuantity(int id)
{
List<DryFoodDonation> dfdlist = await _db.DryFoodDonation.ToListAsync();
var dryfood = dfdlist.Where(d => d.Id == id).FirstOrDefault();
Debug.WriteLine(dryfood.DryFoodName + " " + dryfood.DryFoodRemainQuantity);
return new JsonResult(dryfood.DryFoodRemainQuantity);
}
public async Task<IActionResult> OnGetGetPhoneAdrs(int id)
{
List<User> receiverlist = await _db.User.Where(u => u.UserType.TypeID == 3).ToListAsync();
var selectreceiver = receiverlist.Where(d => d.UserID == id).FirstOrDefault();
Debug.WriteLine(selectreceiver.UserName + " " + selectreceiver.UserPhone);
return new JsonResult(selectreceiver);
}
The jQuery AJAX function in a JavaScript file:
$(document).ready(function () {
$("#receiver").change(function () {
alert('Yes receiver here changed.');
var item = $(this).val();
$.ajax({
type: 'GET',
url: 'Create/?handler=GetPhoneAdrs',
beforeSend: function (xhr) {
xhr.setRequestHeader("XSRF-TOKEN",
$('input:hidden[name="__RequestVerificationToken"]').val());
},
data: {
'id': item
},
contentType: 'application/json; charset=utf-8',
dataType: 'json',
success: function (data) {
$('#receiverphone').html(data.UserPhone);
$('#receiveradrs1').html(data.UserAdrs1);
$('#receiveradrs2').html(data.UserAdrs2);
}
});
});
$("#deliveryitem").change(function () {
alert('Yes item here changed.');
var item = $(this).val();
$.ajax({
type: 'GET',
url: 'Create/?handler=SetMaxQuantity',
beforeSend: function (xhr) {
xhr.setRequestHeader("XSRF-TOKEN",
$('input:hidden[name="__RequestVerificationToken"]').val());
},
data: {
"id": item
},
contentType: 'application/json; charset=utf-8',
dataType: 'json',
success: function (data) {
$("#quantity").attr({
"min": 1,
"max": data
});
}
});
});
});
Please help me with this. I can't solve this problem for a few weeks. Thank you!
// cshtml.cs
const sendMe = async function (someData) {
$.ajax({
type: 'POST',
dataType: 'json',
url: '/ControllerName/MethodNameInController',
data: { someData: someData },
success: function (response) {
if (response != null && response.statusCode == 200) {
..
} else {
..
}
}
});
}
//Controller
[HttpPost("MethodNameInController")]
public IActionResult MethodNameInController([FromForm] string someData) {
..
}

How to update a textbox with the result from a get Request

I have a simple web page designed to show the list of players when a certain team is selected. Currently my API can successfully return all of the players and display it it on the console log, but I am confused on how to you connect that with my div container.
My function returns all the player names as a list
<div class="card">
<div class="card-header"> Player List</div>
<div class="card-body">
<label>Teams</label>
<select id="playerDisplay" onChange="updatePlayerlist();">
<option value=" ">Select a Team</option>
<option value="Fractional">Giants</option>
</select>
<div class="col-sm-7">
<label>Players</label>
<div id="listPlayers"></div>
</div>
</div>
</div>
function updatePlayerslist() {
var playerPick = $("#playerDisplay")[0].value;
$.ajax({
type: 'GET',
url: APICALL,
data: {
'code': playerPick
},
success: function(list) {
if (list.length === 0) {
console.log(list);
playerPick = list;
} else
console.log("EMPTY");
}
})
}
Given that you state:
My function returns all the player names as a list
I'm going to assume that the response is an array of strings. Therefore you can simply loop through that and create the new elements to append to the DOM. Try this:
function updatePlayerslist() {
var playerPick = $("#playerDisplay").val(); // Note use of jQuery here
$.ajax({
type: 'GET',
url: APICALL,
data: {
'code': playerPick
},
success: function(playerNames) {
var html = playerNames.map(function(playerName) {
return `<div>${playerName}</div>`;
});
$('#listPlayers').append(html);
}
})
}
function updatePlayerslist() {
var playerPick = $("#playerDisplay")[0].value;
$.ajax({
type: 'GET',
url: APICALL,
data: {
'code': playerPick
},
success: function(list) {
if (list.length === 0) {
console.log("EMPTY");
}
// Construct the text to be displayed from the `list` data
var textToDisplay = list.join(', ');
// Update the html
$('#listPlayers').html(textToDisplay);
}
})
}
loop through the list and update the element by appending with jQuery
function updatePlayerslist(){
var playerPick = $("#playerDisplay")[0].value;
$.ajax({
type: 'GET',
url: APICALL,
data: {
'code': playerPick
},
success: function(list){
console.log(list);
list.forEach(value => {
$("#listPlayers").append(value)
})
}
})
}

how to submit a form with a local list from javascript

I have a list that i created it in javascript and I want to send it to controller :
function submit1() {
var list_id = [];
var i;
for(i = 0; i < #Model.Count(); i++){
var x =docuzment.getElementsByClassName("bt1")[i].getAttribute("id");
var xxx = document.getElementById(x).style.backgroundColor;
if (xxx == "tomato") {
list_id.push(x);
}
}
$.ajax({
type: "POST",
url: '#Url.Action("add_invitations", "invitations")',
data: {list_id: String},
success: function (data) { alert("SUCCESS"); }
});
}
controller :
public ActionResult add_invitations(List<string> ls )
{
ViewBag.a = ls.Count();
return View();
}
I always get null reference exception for ls>
You are not passing the correct parameter to the action, it expecting to get a parameter named ls, but in your data object you are passing a parameter named list_id.
Try changing it to this:
$.ajax({
type: "POST",
url: '#Url.Action("add_invitations", "invitations")',
data: {ls: list_id},
success: function (data) { alert("SUCCESS"); }
});

innerHTML.value not working?

I've been trying to write a JavaScript program that returns Wikipedia search results. A few days ago, I got it to the point where I could see the item being searched for, as confirmed by the alert() method, but now when I call the same alert() method it just returns "undefined":
$("button").click(function(e){
var search =document.getElementById("test").innerHTML.value;
alert(search);
});
I swear that this is exactly what I had while it was working, so there must be some subtle issue elsewhere. Any help is appreciated, complete code below:
HTML:
Random
<section>
<form>
<br>
<div class="divid">
<input type="text" value='' id="test" >
<button >Search</button>
</div>
</form>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/jqueryui/1.11.3/jquery-ui.min.js"></script>
JavaScript:
$(document).ready(function () {
$("button").click(function(e){
var search =document.getElementById("test").innerHTML.value;
alert(search);
});
var button = $('button');
var toSearch = '';
var searchUrl = "http://en.wikipedia.org/w/api.php"
var x="England";
input.autocomplete({
source: function (request, response) {
$.ajax({
url: searchUrl,
dataType: 'jsonp',
data: {
'action': "opensearch",
'format': "json",
'search': request.term
},
success: function (data) {
response(data[1]);
}
});
}
});
var playListURL = 'http://en.wikipedia.org/w/api.php?format=json&action=query&titles=India&prop=revisions&rvprop=content&callback=?';
$.getJSON(playListURL ,function(data) {
$.each(data.query.pages, function(i, item) {
//alert(item.title);
})
})
$.ajax({
//http://en.wikipedia.org/w/api.php?format=json&action=query&titles=India&prop=revisions&rvprop=content&callback=?
url: '//en.wikipedia.org/w/api.php',
data: { action: 'query', list: 'search', srsearch: "Carl Sagan", format: 'json' },
dataType: 'jsonp',
success:
function (x) {
//alert( x.query.search[0].title);
}
});
})
Use .innerHTML to get the html in a DOM element
Use .value to get the value of an input, textarea, or other form input
.innerHTML.value is not a thing.
If you are using jQuery, try this:
var search = $("#test").html();
alert(search);

How to retrieve the elements of a dropdownlist in jquery and send it with ajax to an MVC Controller in ASP.Net?

I have a select item as follows:
<select id="id_category">
<option> </option>
</select>
In run time there is a tree view used to fill up the select menu as follows:
<script>
$(document).ready(function () {
$('#data').jstree({
"plugins": ["checkbox"]
});
$("#data").on("changed.jstree", function (e, data) {
if (data.selected.length) {
$("#id_category").empty();
$(data.selected).each(function (idx) {
var node = data.instance.get_node(data.selected[idx]);
var s = document.getElementById('id_category');
s.options[s.options.length] = new Option(node.text, '1');
});
}
else
$("#id_category").empty();
});
});
</script>
and the html for the tree is not important now as it works well.
Now, I want when a user click on a button with HTML as follows:
<input id="btn3" type="button" value="Test 3" />
an ajax will be run to send all the items in the select to a controller in MVC as follows:
$("#btn3").click(function () {
$.ajax({
url: "/Products/Test03",
datatype: "text",
data: $.map($('#id_category')[0].options, function( elem ) { return (elem.value || elem.text); }),
type: "POST",
success: function (data) {
$('#testarea').html(data);
},
error: function () {
$("#testarea").html("ERROR");
}
});
});
and the controller:
[HttpPost]
public string Test03(Object str1)
{
// call with two parameters and return them back
this.myRetrievedData = str1;
return str1.ToString();
}
The above did not work with me, when I click on Test3 button nothing happened.
I am not sure how to pass the retrieved items to the function in the controller. Could anyone tell me how to do that?
The below logic must work for you. Many thanks to Mr.Stephen Muecke for assistance.
$("#btn3").click(function () {
var optionsData= $.map($('#id_category')[0].options, function(elem) {
return (elem.value || elem.text);
}); // create a variable to hold all the options array.
$.ajax({
url: "/Products/Test03",
datatype: "text",
data: JSON.stringify(optionsData), //pass this variable to post request as 'options'
contentType: "application/json; charset=utf-8",
type: "POST",
success: function (data) {
$('#testarea').html(data);
},
error: function () {
$("#testarea").html("ERROR");
}
});
});
Then you can have your controller as below.
[HttpPost]
public string Test03(IEnumerable<string> options ) // change here to this
{
//your logic goes here
}
I think it's because you have not added [HttpPost] attribute in your controller function

Categories

Resources