Javascript Select Child With Id Formatting - javascript

Programming a ASP.net webapp to insert an entry into a database on form submit.
I've tried numerous configurations of find() and children() and they either
1) error
2) pass empty strings instead of what I type
This one errors like this:
Whats the correct way to select the individual children of myform?
Javascript (the first block here is the code I'm asking about)
var entry_array = [];
entry_array[0] = $('#myform').children('#01').css().text();
entry_array[1] = $('#myform').children('#02').css().text();
entry_array[2] = $('#myform').children('#03').css().text();
entry_array[3] = $('#myform').children('#04').css().text();
$(document).ready(function () {
$("#myform").submit(function () {
alert("Function ran");
$.ajax({
url: 'Home/SubmitEntry', //(rec)= Controller's-name
//(recieveData) = Action's method name
type: 'POST',
datatype: 'json',
traditional: true,
data: { 'entry_array': entry_array },
success: function(response) {
console.log(response);
},
error: function (response) {
console.log(response);
}
});
alert("Function finished running");
});
});
Controller
[HttpPost]
public ActionResult SubmitEntry(List<String> entry_array)
{
String firstname = entry_array[0];
String lastname = entry_array[1];
String town = entry_array[2];
String order = entry_array[3];
knightsEntities db = new knightsEntities();
int nextiD = 0;
nextiD = db.Apprentenceship_Sheet.ToList().Last().id + 1;
var newApprentenceship_Sheet = new Apprentenceship_Sheet();
newApprentenceship_Sheet.first_name = firstname;
newApprentenceship_Sheet.last_name = lastname;
newApprentenceship_Sheet.hailed_town = town;
newApprentenceship_Sheet.order = order;
newApprentenceship_Sheet.id = nextiD;
db.Apprentenceship_Sheet.Add(newApprentenceship_Sheet);
db.SaveChanges();
return View();
}
View
<script src='https://code.jquery.com/jquery-3.1.0.min.js'></script>
<script src="~/scripts/custom.js"></script>
#{
ViewBag.Title = "Home Page";
}
<div>
<form id= "myform" method="post">
First_name:<br>
<input type="text" id="01" name="firstname"><br>
Last_name:<br>
<input type="text" id="02" name="lastname"><br>
Town:<br>
<input type="text" id="03" name="town"><br>
Order:<br>
<input type="text" id="04" name="order"><br>
<br>
<input type='submit' id="05" name="Submit">
</form>
</div>

You can get the values of the text boxes directly by using $('#01').val(), or if you want refer it with reference to your form. You can use $('#myform').find('#01').val(). It will give the value of the text-box. Here is the jsfiddle for u.
$('#myform').find('#01').val()
$('#01').val()
http://jsfiddle.net/71weztcn/

Related

Javascript function keeps retrieving data from last item in Model list in MVC

I am trying to create functionality that will update a product's quantity in the users shop cart. I am able to populate the ViewModel with the relevant data and display it in a table in the View.
In the script tags, I have two functions, one to increase the quantity of the product and the other to decrease the quantity in increments of 1. Now all works well if there is one product in the list. I receive the correct values. As soon as there are two or more products in the list, whenever the increase or decrease functions are fired, the values (quantity and productId) of the last item in Model.Products are sent to the 'UpdateQuantity' ActionMethod, instead of the values from the inputs in the selected table row.
For example: If there are two products in the list. Product A (Id:1 and Quantity: 3) and Product B(ID:2 and quantity:5), If I click on either the increase or decrease buttons next to Product A's quantity input, the relevant function will pass Product B's values (2 and 5) to the Action Method instead of Product A's values (1 and 3).
I'm assuming that there is a naming convention issue, but I'm unable to figure out why this is happening. Any help would be highly appreciated.
Below is what I have so far:
ViewModel:
public class ShopCartViewModel : BaseViewModel
{
public List<OrderDetail> OrderDetailList { get; set; }
public List<Order> OrderList { get; set; }
public List<Product> Products { get; set; }
}
Controller:
public List<Order> orderList = new List<Order>();
public List<OrderDetail> orderDetailList = new List<OrderDetail>();
public List<Product> productList = new List<Product>();
public ActionResult Index()
{
ShopCartViewModel vm = new ShopCartViewModel();
ConnectToDatabase();
User u = Helpers.GetUser.GetUserDetails();
orderList = GetAllOrdersForCustomer(u.Id);
GetOrderDetails();
vm.OrderList = orderList;
vm.OrderDetailList = orderDetailList;
vm.Products = productList;
return View(vm);
}
[HttpPost]
public ActionResult UpdateQuantity(string quantity, string productId)
{
//do stuff here
}
View:
#foreach(var product in Model.Products)
{
string class_quantity = "quantity_" + product.Id;
string class_productId = "productId_" + product.Id;
<div class="quantity">
<button class="dec-btn p-0" type="submit"><i class="fas fa-caret-left" onclick="q_dec()"></i></button>
<input name="quantity" id="#class_quantity" class=" form-control" type="text" value="#product.Quantity" />
<button class="inc-btn p-0" type="submit"><i class="fas fa-caret-right" onclick="q_inc()"></i></button>
<input name="productId" id="#class_productId" class=" form-control" type="text" value="#product.Id" style="visibility:hidden" />
<script type="text/javascript">
function q_inc(e) {
var p_quantity = $("##class_quantity").val();
var final_quantity = parseInt(p_quantity) + 1;
var p_productId = $("##class_productId").val();
$.ajax({
url: '#Url.Action("UpdateQuantity","ShopCart")',
type: 'POST',
data: {quantity: final_quantity, productId: p_productId },
success: function () {
alert("Increase Success");
}
})
}
function q_dec(e) {
var p_quantity = $("##class_quantity").val();
if (p_quantity >= 2) {
var final_quantity = parseInt(p_quantity) - 1;
}
var p_productId = $("##class_productId").val();
$.ajax({
url: '#Url.Action("UpdateQuantity","ShopCart")',
type: 'POST',
data: {quantity: final_quantity, productId: p_productId },
success: function () {
alert("Decrease Success");
}
})
}
</script>
</div>
}
The problem with your code is that in your loop you are duplicating functions q_inc(e) and q_dec(e)
You should fix your code with something like this:
#foreach(var product in Model.Products)
{
string class_quantity = "quantity_" + product.Id;
string class_productId = "productId_" + product.Id;
<div class="quantity">
<button class="dec-btn p-0" type="button" onclick="q_dec('#class_productId', '#class_quantity")'><i class="fas fa-caret-left"></i></button>
<input name="quantity" id="#class_quantity" class=" form-control" type="text" value="#product.Quantity" />
<button class="inc-btn p-0" type="button" onclick="q_inc('#class_productId', '#class_quantity')"><i class="fas fa-caret-right"></i></button>
<input name="productId" id="#class_productId" class=" form-control" type="text" value="#product.Id" style="visibility:hidden" />
}
<script type="text/javascript">
function q_inc(id, quantity) {
var p_id = $("#" + id);
var p_quantity = $("#" + quantity);
var quantity_val = p_quantity.val()
var final_quantity = parseInt(quantity_val) + 1;
var p_productId = p_id.val();
$.ajax({
url: '#Url.Action("UpdateQuantity","ShopCart")',
type: 'POST',
data: {quantity: final_quantity, productId: p_productId },
success: function () {
alert("Increase Success");
p_quantity.val(final_quantity);
}
})
}
function q_dec(id, quantity) {
// change this function accordingly
</script>

Serialize form and change input names (remove the array part of the input names)

I want to serialize my html form and submit it to my sever via ajax, but before submitting the form, I want to rename the variable names and remove the initiali part, which is: BranchViewModels[0]. for example, I want to change:
change: BranchViewModels[0].BranchName to: BranchName
change: BranchViewModels[1].AddressViewModel.AddressId to : AddressViewModel.AddressId
Basically when I generate form, all the input names are rendered as an array, but before submitting the form, I want to get rid of array section of the input name (BranchViewModels[0]. in this example).
I have explained why I am doing this here
I have also created a jsfiddle for the following example.
function updateBranch() {
$('.save-branch-button').click(function() {
var branchForm = $(this).closest('form');
var serializedform = branchForm.find('.form :input').serialize();
alert('I want to change the input names in this serialized form: \n\n' + serializedform );
// 1. iterated through serialized form
//
// remove BranchViewModels[i]. from the name, e.g.
// replace: BranchViewModels[0].BranchName
// with: BranchName
// 2. Submit the form
/* $.ajax({
url: "/my-server",
data: {branchViewModel: <-- serialized model},
dataType: 'json',
type: "POST"}); */
});
}
jQuery(document).ready(function($) {
updateBranch();
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<form onsubmit="return false;" novalidate="novalidate">
<div class="form">
<div class="form-group">
<label>Branch name</label>
<input class="form-control" data-val="true" id="BranchViewModels_0__BranchName" name="BranchViewModels[0].BranchName" type="text" value="branch 1">
</div>
<hr />
<div class="form-group">
<label>Branch location</label>
<div>
<input data-val="true" id="BranchViewModels_0__AddressViewModel_AddressId" name="BranchViewModels[0].AddressViewModel.AddressId" value="1956">
</div>
<div>
<input class="address-street-address" data-val="true" id="BranchViewModels_0__AddressViewModel_StreetAddress" name="BranchViewModels[0].AddressViewModel.StreetAddress" value="Wellington 6011, New Zealand">
</div>
</div>
<input type="button" class="btn btn-primary-action save-branch-button" value="Save">
</div>
</form>
function updateBranch() {
$('.save-branch-button').click(function() {
var branchForm = $(this).closest('form');
var serializedform = branchForm.find('.form :input').serializeArray();
console.log(serializedform);
const obj = {};
for(let d of serializedform){
obj[d.name.split('.').pop()] = d.value
}
console.log(obj);
}
Return serialize data to Deserialize then change to you want anything Hope this help you.
console.log(deparam(serializedform));
function deparam(query) {
var pairs, i, keyValuePair, key, value, map = {};
// remove leading question mark if its there
if (query.slice(0, 1) === '?') {
query = query.slice(1);
}
if (query !== '') {
pairs = query.split('&');
for (i = 0; i < pairs.length; i += 1) {
keyValuePair = pairs[i].split('=');
key = decodeURIComponent(keyValuePair[0]);
value = (keyValuePair.length > 1) ? decodeURIComponent(keyValuePair[1]) : undefined;
map[key] = value;
}
}
return map;
}

AJAX send form with data and multiple image to asp.net mvc action

It has been like two days. I have been searching on the web, but I cant figure out the solution.
I have some input fields, where I can Insert text and select images. They are variable, that means if you want more fields to add more products you can click on "+" and I add another field set.
When I click on "Salva e Prosegui" and pass all the data to my ASP.MVC action in the controller.
I tried different ways but I'm not able to pass the images.
HTML:
<div class="fields-container">
<div class="row">
<div class="col-md-2">
<input type="text" name="nomecolore" placeholder="Nome Colore" class="form-control" />
</div>
<div class="col-md-1">
<input type="text" name="codicecolore" placeholder="Codice Colore" class="form-control" />
</div>
<div class="col-md-4">
<input type="file" name="filefronte" class="form-control filestyle" data-text="Foto Fronte" data-btnClass="btn-primary form-control" data-buttonBefore="true">
</div>
<div class="col-md-4">
<input type="file" name="fileretro" class="form-control filestyle" data-text="Foto Retro" data-btnClass="btn-primary form-control" data-buttonBefore="true">
</div>
<div class="col-md-1">
<button class="btn btn-success add-more form-control" type="button"><i class="glyphicon glyphicon-plus"></i></button>
</div>
</div>
JS:
$('#step-2-next').click(function () {
var ListaNomiColori = $(".fields-container :input[name=nomecolore]");
var ListaCodiciColori = $(".fields-container :input[name=codicecolore]");
var ListaImmaginiFronte = $(".fields-container :input[name=filefronte]");
var ListaImmaginiRetro = $(".fields-container :input[name=fileretro]");
var ID_Prodotto = "1";
for (i = 0; i < ListaNomiColori.length; i++) {
var formData = new FormData();
var nome = ListaNomiColori[i].value;
var codice = ListaCodiciColori[i].value;
var fronte = ListaImmaginiFronte[i].files[0];
var retro = ListaImmaginiRetro[i].files[0];
formData.append("NomeColore", nome);
formData.append("CodiceColore", codice);
formData.append("Foto", fronte);
formData.append("Foto", retro);
formData.append("ID_Prodotto", ID_Prodotto);
$.ajax({
url: _NuovoProdottoCaricaModelli,
data: formData,``
processData: false,
contentType: false,
success: function (res) {
alert('succes!!');
},
error: function (res) {
alert("errror");
}
})
}
});
Controller:
public JsonResult NuovoProdottoCaricaModelli(FormCollection form)
{
////code here
}
My logic is:
I get how many field sets I have and for each one I get the value and call the server for the upload. For each field set I have 2 text input, 2 file input. I also have to pass the ID to a third text field.
Thank you in advance.
Thanks to darloopkat. I found a way to do that.
Here below my edits:
js:
$('#step-2-next').click(function () {
var ListaNomiColori = $(".fields-container :input[name=nomecolore]");
var ListaCodiciColori = $(".fields-container :input[name=codicecolore]");
var ListaImmaginiFronte = $(".fields-container :input[name=filefronte]");
var ListaImmaginiRetro = $(".fields-container :input[name=fileretro]");
var ID_Prodotto = "1";
for (i = 0; i < ListaNomiColori.length; i++) {
var formData = new FormData();
var nome = ListaNomiColori[i].value;
var codice = ListaCodiciColori[i].value;
var fronte = ListaImmaginiFronte[i].files[0];
var retro = ListaImmaginiRetro[i].files[0];
formData.append("NomeColore", nome);
formData.append("CodiceColore", codice);
formData.append("Foto", fronte);
formData.append("Foto", retro);
formData.append("ID_Prodotto", ID_Prodotto);
$.ajax({
url: _NuovoProdottoCaricaModelli,
data: formData,
type: "POST",
processData: false,
contentType: false,
success: function (res) {
alert('succes!!');
},
error: function (res) {
alert("errror");
}
})
}
});
mvc action:
[HttpPost]
public ActionResult NuovoProdottoCaricaModelli()
{
string Nome = Request["NomeColore"];
string CodiceColore = Request["NomeColore"];
var Fronte = Request.Files[0];
var NomeFronte = Path.GetFileName(Fronte.FileName);
var Retro = Request.Files[1];
var NomeRetro = Path.GetFileName(Retro.FileName);
return Json("");
}

Catching a textbox value which is stored in a variable

This is my controller.
public class HomeController : Controller
{
public static string commString = "";
public HomeController()
{
FWUtility.connString = "data source=.;initial catalog=northwind;uid=sa;password=123";
}
public ActionResult Index()
{
return View();
}
public static DataTable GetData(string customerID)
{
string strFilter = "'" + customerID + "%'";
commString = "select * from customers where CustomerID like " + strFilter;
return FWUtility.GetDataTable(commString);
}
This is the view.
<script type="text/javascript">
function buttonClick() {
var value = $('#text1').val();
alert('#HomeController.GetData("D").Rows.Count.ToString()');
}
</script>
<input type="text" id="text1" value="A" />
<input type="text" id="text2" />
<input type="button" value="Show" id="button1" onclick="buttonClick()" />
I want to catch the value which is stored in the textbox and display it in the alert box, where I have mentioned "D". In my controller I have a sql query assigned.And here I am calling the controller. My out put will be suppose I put "A" inside the text box and click the button, i will get the count of all the names starting with letter "A". Like this
It's not clear from the question, but assuming you want more than a simple alert(value), then:
I suggest that you add an additional action to go with the GetData function to return row count directly:
public ActionResult GetDataRowCount(string id)
{
var count = GetData(id).Rows.Count;
return new JsonResult
{
Data = new { count },
JsonRequestBehavior = JsonRequestBehavior.AllowGet
};
}
then you can use jquery ajax to get this value from the controller:
<script type="text/javascript">
function buttonClick() {
var value = $('#text1').val();
$.get({
url: '#Url.Action("GetDataRowCount", "Home")',
data: { id = value },
success: function(result) {
alert(result.count);
}
});
}
</script>
<input type="text" id="text1" value="A" />
<input type="button" value="Show" id="button1" onclick="buttonClick()" />
Well, done it at last. Here is the solution.
<script src="~/Scripts/jquery-1.8.2.js"></script>
<script type="text/javascript">
function buttonClick() {
var value = $('#text1').val();
$.ajax({
url: '../Home/GetData',
method: 'POST',
data: { customerID: value },
success: function (data) {
result = data;
alert(result);
},
});
}
</script>
<input type="text" id="text1" value="A" />
<input type="button" value="Show" id="button1" onclick="buttonClick()" />

why when my action returns a view - it passes first through a javascript function

In the Index view I just have a button with a javascript function for when it's clicked:
<script>
function AddCat() {
$.ajax({
type: "GET",
url: '#Url.Action("AddCategory")',
data: {},
});
}
</script>
#Html.DropDownList("Languages", new SelectList(Model.lstLanguages, "LanguageID", "Name", Session["langID"] ?? "1"), new { id = "ddlLanguages" })
<div id="categoriesPlace"></div>
<input type="button" id="btnAddCategory" onclick="AddCat()" value="AddCategory" />
When I click on the button, as you see I should be redirected to the AddCategory action, which adds a record in the database and returns the AddCategory view. The problem is that when it reaches the drop-down in my AddCategory view, it goes straight to the Addbtn_CLick() function as if it's clicked and then it redirects me to the Index action. Can you explain this behavior?
So, here is my CategoryController:
public class CategoryController : Controller
{
public ActionResult AddCategory()
{
CategoryViewModel vm = new CategoryViewModel();
vm.AddNewCategory();
return View(vm);
}
public ActionResult AddCategoriesLanguages(int catID, int lanID, string title, string shrtDescription, string description)
{
CategoryViewModel vm = new CategoryViewModel();
vm.AddCategoriesLanguages(catID, lanID, title, shrtDescription, description);
return RedirectToAction("Index");
}
}
And, here is my AddCategory view:
#model Onion.Web.ViewModels.CategoryViewModel
#{
ViewBag.Title = "AddCategory";
}
<h2>AddCategory</h2>
#Html.DropDownList("Languages", new SelectList(Model.lstLanguages, "LanguageID", "Name",#HttpContext.Current.Session["langID"]),new { id = "ddlLanguages" })
<br />
<label for="txbTitle">Title:</label>
<input type="text" id="txbTitle"/>
<br />
<label for="txbShortDescription">Short Description:</label>
<input type="text" id="txbShortDescription" />
<br />
<br />
<input type="button" id="btnAdd" onclick="btnAdd_Click" value="Add" />
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.4.2/jquery.min.js" type="text/javascript"></script>
<script>
function btnAdd_Click() {
$.ajax({
type: "GET",
url: '#Url.Action("AddCategoriesLanguages")' + '?catID=' +#Model.newCategoryID +'&lanID=' + $("#ddlLanguages").val() + '&title=' + $('#txbTitle').val() + '&shrtDescription=' + $('#txbShortDescription').val() + '&Description=' + $('#txbDescription').val(),
data: {}
});
}
</script>
In your AddCategory view, try changing your button's onclick attribute to include the function name and parenthesis as shown below:
<input type="button" id="btnAdd" onclick="btnAdd_Click()" value="Add" />
I am not 100% sure if that is the issue, but it stood out to me.

Categories