Knockoutjs foreach n rows check if dropdown has value - javascript

I have this html markup:
<!-- ko foreach: Orders -->
<div class="row">
<div>
<select class="form-control" data-bind="attr: { id: 'prefix_' + $index() }, options: TeacherNames, optionsValue: 'TeacherId', optionsText: 'TeacherName', optionsCaption: 'Choose Teacher', event: { change: $root.teacherChanged }">
</select>
</div>
<div>
<a href='#' data-bind="click: $root.RequestImage" class="green-btn blue pull-right">
<span class="glyphicon glyphicon-cloud-download"></span> Download
</a>
</div>
</div>
<!-- /ko -->
There will be n number of items in the foreach loop, that will not be known in the moment of development.
What I want to do is when the $root.RequestImage is clicked, the code needs to check if there is selection made in the respected dropdown for that row, if the selection is made then proceed further, otherwise display alert box with 'error' message.
So in the RequestImage that action should happen, this is the RequestImage function currently:
self.RequestImage = function () {
};
How can I achieve this?
Update
OrdersVM:
var self = this;
self.Orders = ko.observableArray([]);
$.ajax({
type: "POST", url: "/webservices/InfoWS.asmx/GetOrders",
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (data) {
if (data.d != null) {
var orderIds = [];
ko.utils.arrayForEach(data.d, function (item) {
item._teacherOrders = ko.observable();
$.ajax({
type: "POST",
url: "/webservices/InfoWS.asmx/GetTeachersForMyAccount",
contentType: "application/json; charset=utf-8",
data: "{'orderId': " + JSON.stringify(item.OrderId) + "}",
dataType: "json",
success: function (data) {
if (data) {
return item._teacherOrders(data.d);
}
},
error: function (n) {
alert('Error retrieving teachers for orders, please try again.');
}
});
item.TeacherNames = ko.computed(function () {
return item._teacherOrders();
});
self.Orders.push(item);
orderIds.push(item.OrderId);
});
}
},
error: function (data) {
var response = JSON.parse(data.responseText);
console.log("error retrieving orders:" + response.Message);
}
});

I would do it this way:
add an observable selectedTeacher to every order object
add value: selectedTeacher to your selects:
<select class="form-control" data-bind="attr: { id: 'prefix_' + $index() }, options: TeacherNames, optionsValue: 'TeacherId', ..., value: selectedTeacher"></select>
check that observable in your RequestImage event
if ( !data.selectedTeacher() ) {
alert('Error: select teacher')
} else {
alert('Success')
}
A working demo - Fiddle

Related

Ajax not working on iphone but working on pc

I have a dropdown and when I select an option I run one ajax call, on pc is working as expected but on iPhone is not triggering the ajax, it goes to the function and I know this because I added alerts.
When i click 13,14,15 is not working. At 9,10,11,12 is working.
<div class="row" id="type">
Selected type: #Html.DropDownListFor(model => model.GymType, listItems, new { id = "GymType", onchange = "getBookTime();" })
</div>
<div id="timesList" style="display:none;margin:auto">
Selecte time: <select id="states_ddl" name="states_ddl" class="cs3 input-small" > </select>
</div>
function getBookTime(e) {
var selectedtype = $('#GymType').val();
alert(selectedtype);
var selectedDate = $('#date').text();
$.ajax({
type: "GET",
async: false, //This makes the JQuery below wait until $.ajax() call is finished
cache: false,
headers: { "cache-control": "no-cache" },
url: '/Home/GetBookTime/',
data: { date: selectedDate, type: selectedtype },
success: function (data) {
if (data.message != undefined) {
alert(data.message);
$('#error').show();
document.getElementById("errormsg").innerHTML = data.message;
}
else {
alert(data);
$('#error').hide();
$("#timesList").show();
var options = $("#states_ddl");
options.empty();
$.each(data, function (index, item) {
options.append($("<option />").val(item).text(item));
});
}
$("#submitbtn").show();
},
error: function (xhr, status, error) {
var err = eval("(" + xhr.responseText + ")");
alert(err.Message);
}
})
}

How can I serialize a form in JavaScript asp.net

I am using some javascript to post my form but I dont want to have to submit each form field is there a way I can serlize this to an object in .net so that it will bring in all the form contents.
section Scripts {
<script>
function confirmEdit() {
swal({
title: "MIS",
text: "Case Created your Case Number is " + $("#Id").val(),
icon: "warning",
buttons: true,
dangerMode: true,
}).then((willUpdate) => {
if (willUpdate) {
$.ajax({
url: "/tests/edit/" + $("#Id").val(),
type: "POST",
data: {
Id: $("#Id").val(),
Name: $("#Name").val()
},
dataType: "html",
success: function () {
swal("Done!", "It was succesfully edited!", "success")
.then((success) => {
window.location.href = "/tests/index"
});
},
error: function (xhr, ajaxOptions, thrownError) {
swal("Error updating!", "Please try again", "error");
}
});
}
});
}
</script>
}
asp.net core will automatically bind json data using the [FromBody] attribute.
data: {
id: $("#Id").val(),
name: $("#Name").val()
},
and then in your controller
[HttpPost("/tests/edit/")]
public IActionResult Process([FromBody] MyData data){ ... }
where MyData is
public class MyData
{
public string Id {get;set;}
public string Name {get;set;}
}
section Scripts { function confirmEdit() {
swal({ title: "MIS", text: "Case Created your Case Number is " + $("#Id").val(), icon: "warning", buttons: true, dangerMode: true, }).then((willUpdate) => { if (willUpdate) {
var obj = { Id: $("#Id").val(), Name: $("#Name").val() }
$.ajax({ url: "/tests/edit/" + $("#Id").val(), type: "POST", data: JSON.Stringify(obj), dataType: "html", success: function () { swal("Done!", "It was succesfully edited!", "success") .then((success) => { window.location.href = "/tests/index" }); }, error: function (xhr, ajaxOptions, thrownError) { swal("Error updating!", "Please try again", "error"); } }); } }); } }
in c# use
public ActionResult FormPost(MyData obj)
Please refer to the following methods to submit the form data to action method:
using the serialize() method to serialize the controls within the form.
#model MVCSample.Models.OrderViewModel
<h4>OrderViewModel</h4>
<hr />
<div class="row">
<div class="col-md-4">
<form asp-action="Showsummary" asp-controller="Home" method="post" class="signup-form">
<div asp-validation-summary="ModelOnly" class="text-danger"></div>
<div class="form-group">
<label asp-for="OrderId" class="control-label"></label>
<input asp-for="OrderId" class="form-control" />
<span asp-validation-for="OrderId" class="text-danger"></span>
</div>
<div class="form-group">
<label asp-for="OrderName" class="control-label"></label>
<input asp-for="OrderName" class="form-control" />
<span asp-validation-for="OrderName" class="text-danger"></span>
</div>
<div id="packages">
#for (int i = 0; i < Model.Packages.Count; i++)
{
<div class="form-group">
<label asp-for="#Model.Packages[i].Pid" class="control-label"></label>
<input asp-for="#Model.Packages[i].Pid" class="form-control" />
<span asp-validation-for="#Model.Packages[i].Pid" class="text-danger"></span>
<br />
<label asp-for="#Model.Packages[i].PackageTitle" class="control-label"></label>
<input asp-for="#Model.Packages[i].PackageTitle" class="form-control" />
<span asp-validation-for="#Model.Packages[i].PackageTitle" class="text-danger"></span>
</div>
}
</div>
</form>
</div>
</div>
<div>
<input type="button" id="summary" value="Summary" />
<div id="page_3">
</div>
</div>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
<script>
$(function () {
$("#summary").click(function () {
console.log("calling summary");
event.preventDefault();
$.ajax({
type: "POST",
url: "/Home/Showsummary", //remember change the controller to your owns.
data: $("form.signup-form").serialize(),
success: function (data) {
console.log(data)
},
failure: function (response) {
console.log(response.responseText);
},
error: function (response) {
console.log(response.responseText);
}
});
});
});
</script>
Code the the action method:
[HttpPost]
public PartialViewResult Showsummary(OrderViewModel model)
{
try
{
//...
return PartialView("OrderSummary", model);
}
catch
{
return PartialView("OrderSummary", model);
}
}
After clicking the button, the result like this:
As we can see that, we could get the element's value in the form and even the nested entity.
Note: Only "successful controls" are serialized to the string. No submit button value is serialized since the form was not submitted using a button. For a form element's value to be included in the serialized string, the element must have a name attribute. Values from checkboxes and radio buttons (inputs of type "radio" or "checkbox") are included only if they are checked. Data from file select elements is not serialized.
Create a JavaScript object, and post it to action method.
Change the JavaScript script as below:
$(function () {
$("#summary").click(function () {
console.log("calling summary");
event.preventDefault();
//create a object to store the entered value.
var OrderViewModel = {};
//using jquery to get the entered value.
OrderViewModel.OrderId = $("input[name='OrderId']").val();
OrderViewModel.OrderName = $("input[name='OrderName']").val();
var packages = [];
//var count = $("#packages>.form-group").length; //you could use it to check the package count
$("#packages>.form-group").each(function (index, item) {
var package = {}
package.Pid = $(item).find("input[name='Packages[" + index + "].Pid']").val();
package.PackageTitle = $(item).find("input[name='Packages[" + index + "].PackageTitle']").val();
packages.push(package);
});
//add the nested entity
OrderViewModel.Packages = packages;
$.ajax({
type: "POST",
url: "/Home/Showsummary", //remember change the controller to your owns.
data: OrderViewModel,
success: function (data) {
console.log(data)
$('#page_3').html(data);
},
failure: function (response) {
console.log(response.responseText);
},
error: function (response) {
console.log(response.responseText);
}
});
});
});
By using the above code, I could also get the submit entity, you could refer to it.

Cascading dropdown in knockout.js

I'm trying to populate another dropdownlist from a dropdown list, i keep getting error "TypeError: Unable to process binding "value: function (){return CompanySelected }" and "http://localhost/xxx/api/Transaction/LoadInsurancePolicies/undefined 400 (Bad Request)". Insurance Policy must be populated when Insurance company is chosen. this is the code below
self.InsuranceCompanyId = ko.observable();
self._companySelected= ko.observable(null);
self.CompanySelected = ko.computed({
read: function () {return this._companySelected() },
write: function (value) {
$.ajax({
url: baseUrl + 'api/Transaction/LoadInsurancePolicies/' +
value.InsuranceCompanyId,
type: 'GET',
headers: { 'Access-Control-Allow-Origin': '*' },
dataType: 'json',
success: function (data) {
if (data.Successfull == 1)
{
self.AllPolicies(data.Model); } },
error: function (request, error) {
}
});
this._companySelected(value);
},
owner: this
});
self.AllInsuranceCompanies = ko.observableArray([]);
self.AllPolicies = ko.observableArray([]);
self.LoadInsuranceCompanies = function () {
$.ajax({
url: baseUrl + 'api/Transaction/LoadInsuranceCompanies',
type: 'GET',
headers: { 'Access-Control-Allow-Origin': '*' },
dataType: 'json',
success: function (data) {
// console.log(data);
if (data.Successfull == 1) {
self.AllInsuranceCompanies(data.Model);
console.log(data);
}
},
error: function (request, error) {
console.log(error);
}
});
}
self.LoadInsuranceCompanies();
this is my view
<div class="form-group" data-bind="visible:(InputOption()==0)">
<label for="InputTxt" class="control-label col-md-4">Insurance
Company</label>
<div class="col-md-8">
<select data-bind="options: AllInsuranceCompanies,
optionsText: 'Name',
optionsValue:'Id',
optionsCaption: 'Choose...',
value:CompanySelected,
valueUpdate:'change'" class="form-control">
</select>
</div>
</div>
<div class="form-group" data-bind="visible: (InputOption()==0)">
<label for="InputTxt" class="control-label col-md-
4">InsurancePolicy</label>
<div class="col-md-8">
<select data-bind="options: AllPolicies,
optionsText: 'Name',
optionsValue:'Id',
value: selectedPolicy,
optionsCaption: 'Choose...'" class="form-control">
</select>
</div>
</div>
The following are probably the problems in your code.
self.CompanySelected is defined before self.AllPolicies. This will cause to have a runtime error since ko.computed automatically runs when it is defined. This is based on knockout documentation. Solution: try defining all ko.observable before all ko.computed or atleast put self.AllPolicies before self.CompanySelected.
Since the ko.computed automatically runs, and the value of self.CompanySelected is undefined, you will also have an undefined InsuranceCompanyId in your api call and this will result in Bad request 400. Solution: try adding a guard before calling your api. if(value){....}
In your html bindings, you put optionsValue: 'Id'. This will result in knockout trying to find an Id property in your model which probably does not exist. Solution: remove optionsValue:'Id' from your bindings so that the value when changing option will be the model object itself and not just the Id.
Here is a sample fiddle: https://jsfiddle.net/przquhcf/1/ which implements the solutions above.
Note: I just substituted setTimeout for your api calls since i dont have access to them. Dont worry about this part.
Your solution gave me an idea.I passed a function(value) and the value will be the selected Id,add it to the api as a parameter and it gets me the results.
self.insuranceCompanyId = ko.observable('');
self.selectedPolicy = ko.observable();
self._companySelected = ko.observable();
self.CompanySelected = ko.pureComputed({
read: function () {
return this._companySelected()
},
write: function (value) {
console.log("inside write", value)
if (value) {
console.log('data');
$.ajax({
url: baseUrl + "api/Transaction/LoadInsurancePolicies/" +
value,
type: 'GET',
headers: { 'Access-Control-Allow-Origin': '*' },
dataType: 'json',
success: function (data) {
if (data.Successfull == 1) {
self.AllPolicies(data.Model);
console.log(value);
}
},
error: function (request, error) {
console.log(error);
}
});
this._companySelected(value);
}
},
owner: this
});
self.LoadInsuranceCompanies();

Add autocomplete input control as part of knockout view model

I have the following markup where any skills that exists as part of my view model are displayed. I have a button in my html that runs the self.create function in my view model to create a new item in the EmployeeSkillsArray IF the user decides to add a new skill. The input control below works as expected when the autocomplete portion is removed, however, my goal is to allow a user to begin typing a skill and if that skill exists allow them to select it from autocomplete. It is THIS autocomplete functionality that seems to be causing the issue within the EmployeeSkillsArray. I am able to see autocomplete working when an input control is placed OUTSIDE the array in my markup.
Is there a way to accomplish this goal of having an input control inside the foreach loop to display an item if it is in the array, otherwise allow the user to use autocomplete?
<tbody data-bind="foreach: EmployeeSkillsArray">
<tr>
<td class="col-xs-2">
<input type="hidden" data-bind="value: EmployeeSkillId, visible: false" />
<div class="input-group">
<input type="text" id="skillName" class="form-control" placeholder="Type a skill..." data-bind="value: SkillName, id: SkillsId, autoComplete: { selected: $root.selectedOption, options: $root.options }" /> <!-- corrected based on answer provided by f_martinez -->
</div>
</td>
</tr>
</tbody>
I am getting an Uncaught ReferenceError: Unable to process binding "autoComplete: function (){return { selected:selectedOption,options:options} }"
Message: selectedOption is not defined
I DO have selectionOption defined as part of my view model....
$(function () {
ko.bindingHandlers.autoComplete = {
init: function (element, valueAccessor, allBindings, viewModel, bindingContext) {
var settings = valueAccessor();
var selectedOption = settings.selected;
var options = settings.options;
var updateElementValueWithLabel = function (event, ui) {
event.preventDefault();
$(element).val(ui.item.label);
if(typeof ui.item !== "undefined") {
selectedOption(ui.item);
}
};
$(element).autocomplete({
source: options,
select: function (event, ui) {
updateElementValueWithLabel(event, ui);
},
focus: function (event, ui) {
updateElementValueWithLabel(event, ui);
},
change: function (event, ui) {
updateElementValueWithLabel(event, ui);
}
});
}
};
function ActivityViewModel() {
var self = this;
var remoteData;
$.ajax({
url: '#Url.Action("GetAllSkills", "EmployeeSkills")',
data: { },
async: false,
dataType: 'json',
type: 'GET',
contentType: "application/json; charset=utf-8",
success: function (data) {
remoteData = ($.map(data, function (item) {
return {
id: item.SkillId,
name: item.SkillName
};
}));
}
});
self.skills = remoteData;
self.selectedOption = ko.observable('');
self.options = ($.map(self.skills, function (element) {
return {
label: element.name,
value: element.id,
object: element
};
}));
var EmployeeSkill = {
EmployeeSkillId: self.EmployeeSkillId,
EmployeeId: self.EmployeeId,
SkillsId: self.SkillsId,
SkillName: self.SkillName,
SkillLevelId: self.SkillLevelId,
ApplicationUsed: self.ApplicationUsed,
selectedOption: self.selectedOption,
options: self.options
};
self.EmployeeSkill = ko.observable();
self.EmployeeSkillsArray = ko.observableArray();
$.ajax({
url: '#Url.Action("GetAllEmployeeSkills", "EmployeeSkills")',
cache: false,
type: 'POST',
contentType: 'application/json; charset=utf-8',
data: ko.toJSON({ 'UserId' : employeeId, 'ActivityHistoryId' : activityHistoryId }),
success: function (data) {
self.EmployeeSkillsArray(data); // Put the response in ObservableArray
}
});
self.cloneRow = function () {
$.ajax({
url: '#Url.Action("AddSkill", "EmployeeSkills")',
cache: false,
type: 'POST',
contentType: 'application/json; charset=utf-8',
data: {},
success: function (data) {
self.EmployeeSkillsArray.push(data);
}
}).fail(function (xhr, textStatus, err) {
alert(err);
});
}
}
var viewModel = new ActivityViewModel();
ko.applyBindings(viewModel);
});

AJAX Delete Not Working Entity Framework

I wonder why its not working, here is the code
View
<input type="button" value="Delete" onclick="deletefunction(#item.PhotoId)"/>
Controller
[HttpPost]
public ActionResult Delete(int photoid)
{
var imgDelete = db.Photos.Where(x => x.PhotoId == photoid).FirstOrDefault();
if (imgDelete == null)
{
return new HttpStatusCodeResult(HttpStatusCode.BadRequest);
}
db.Photos.Remove(imgDelete);
db.SaveChanges();
System.IO.File.Delete(AppDomain.CurrentDomain.BaseDirectory + imgDelete.ImagePath);
System.IO.File.Delete(AppDomain.CurrentDomain.BaseDirectory + imgDelete.ThumbPath);
return null;
}
JQUERY/AJAX
<script type="text/javascript">
$(document).ready(function () {
function deletefunction(photoid) {
$.ajax({
url: '#Url.Action("Delete")',
type: 'POST',
data: { photoid: photoid },
success: function (result) {
alert: ("Success")
},
error: {
alert: ("Error")
}
});
};
});
</script>
im new to jquery and ajax, im trying to delete the photo without refreshing the page, am i in the correct path?
I would suggest to attach click event to your button instead of writing javascript in markup. Consider the below markup:
<input type="button" class="delete" value="Delete" data-picid="#item.photoId"/>
Now attach a click event to .delete as below:
$('.delete').on('click',function(){
var photoId=$(this).attr('data-picid');//gets your photoid
$.ajax({
url: '#Url.Action("Delete")',
type: 'POST',
data: JSON.stringify({ photoid: photoId }),
contentType: "application/json; charset=utf-8",
dataType: "json", //return type you are expecting from server
success: function (result) {
//access message from server as result.message and display proper message to user
alert: ("Success")
},
error: {
alert: ("Error")
}
});
});
Your Controller then:
[HttpPost]
public ActionResult Delete(int photoid)
{
var imgDelete = db.Photos.Where(x => x.PhotoId == photoid).FirstOrDefault();
if (imgDelete == null)
{
return Json(new{ message=false},JsonRequestBehavior.AllowGet);//return false in message variable
}
db.Photos.Remove(imgDelete);
db.SaveChanges();
System.IO.File.Delete(AppDomain.CurrentDomain.BaseDirectory + imgDelete.ImagePath);
System.IO.File.Delete(AppDomain.CurrentDomain.BaseDirectory + imgDelete.ThumbPath);
return Json(new{ message=false},JsonRequestBehavior.AllowGet); //return true if everything is fine
}
Once photo is deleted based on the success or failure your can do it as below in success of ajax, but before that store a reference to yourbutton` as below:
$('.delete').on('click',function(){
var photoId=$(this).attr('data-picid');//gets your photoid
var $this=$(this);
$.ajax({
url: '#Url.Action("Delete")',
type: 'POST',
data: JSON.stringify({ photoid: photoId }),
contentType: "application/json; charset=utf-8",
dataType: "json", //return type you are expecting from server
success: function (result) {
if(result.message)
{
$this.closest('yourrootparentselector').remove();
//here yourrootparentselector will be the element which holds all
//your photo and delete button too
}
},
error: {
alert: ("Error")
}
});
});
UPDATE
Based on your given mark up you I suggest to add one more root parent for your each image and delete button as below:
<div style="margin-top: 17px;">
<div id="links">
#foreach (var item in Model.Content)
{
<div class="rootparent"> <!--rootparent here, you can give any classname-->
<a href="#item.ImagePath" title="#item.Description" data-gallery>
<img src="#item.ThumbPath" alt="#item.Description" class="img-rounded" style="margin-bottom:7px;" />
</a>
<input type="button" class="delete" value="Delete" data-picid="#item.PhotoId" />
</div>
}
</div>
</div>
Now you can write this in success
$this.closest('.rootparent').remove()
Try this.
<script type="text/javascript">
$(document).ready(function () {
});
function deletefunction(photoid) {
$.ajax({
url: '#Url.Action("Delete")',
type: 'POST',
contentType: "application/json; charset=utf-8",
dataType: "json",
data: { photoid: photoid },
success: function (result) {
alert: ("Success")
},
error: {
alert: ("Error")
}
});
}
</script>

Categories