How to initialize json data in knockout js - json

I am new bie on knockout js.i create a crud operation one page app in which you click on add field a form appear you add the data and click on add button it add the data and if you click on save button it show the data in json format but when i am clicking on my save button i just want to save the data which is in form at that time not the whole data.i am able to do this functionality on click of delete but dont know how to perform on click of save here is whole structure
<html>
<head>
<script type="text/javascript" src="jquery.min.js"></script>
<script type="text/javascript" src="knockout-3.1.0.js"></script>
</head>
<body>
<table style="width:100%;" data-bind="visible:showFields">
<tbody>
<tr>
<th style="width:100px;">Branch </th>
<th style="width:100px;">Enter Value</th>
</tr>
</tbody>
<tr>
<td>Branch ID (int):</td>
<td>
<input data-bind="value: BranchId" />
</td> <!--,valueUpdate:'keypress'-->
</tr>
<tr>
<td>Name :</td>
<td>
<input data-bind="value: Name" /></td>
</tr>
<tr>
<td>Description :</td>
<td>
<input data-bind="value: Description" /></td>
</tr>
<tr>
<td>Template :</td>
<td>
<select data-bind="options: Templates, value:
Template, optionsCaption: 'Select Template...'"></select></td>
</tr>
<tr>
<td>MetaKeyword :</td>
<td>
<input data-bind="value: MetaKeyword" /></td>
</tr>
<tr>
<td>MetaDescription :</td>
<td>
<input data-bind="value: MetaDescription" /></td>
</tr>
<tr>
<td>MetaTitle :</td>
<td>
<input data-bind="value: MetaTitle" /></td>
</tr>
<tr>
<td>EnableSearch :</td>
<td>
<select data-bind="options: EnableSearchs, value:
EnableSearch, optionsCaption: 'Select Search...'"></select>
</td>
</tr>
<tr>
<td colspan="3">
<button type="button" data-bind="click:
AddBranch">Add Branch</button>
<button type="button" data-bind="click:
SaveBranch">Save Branch</button>
</td>
</tr>
</table>
</div>
<div style="width:70%;float:left;display:inline-block;" data-bind="visible:show">
<h2>List of Branches</h2>
<table style="width:100%;" data-bind="visible: Branches().length > 0" border="0">
<tr>
<th>Branch Id</th>
<th>First Name</th>
<th>Last Name</th>
<th>Template</th>
<th>MetaKeyword</th>
<th>MetaDescription</th>
<th>MetaTitle</th>
<th>EnableSearch</th>
</tr>
<tbody data-bind="foreach: Branches">
<tr>
<td><span data-bind="text: BranchId" /></td>
<td>
<span data-bind="text: Name" /></td>
<td>
<span data-bind="text: Description" /></td>
<td>
<select data-bind="options: $root.Templates,
value: Template"></select></td>
<td>
<span data-bind="text: MetaKeyword" /></td>
<td>
<span data-bind="text: MetaDescription" /></td>
<td>
<span data-bind="text: MetaTitle" />
</td>
<td>
<select data-bind="options: $root.EnableSearchs,
value: EnableSearch"></select>
</td>
<td><a href="#" data-bind="click: $root.
DeleteBranch">Delete</a></td>
<td>edit</td>
</tr>
</tbody>
</table>
AddFields
</div>
</body>
<script>
function Branch(data) {
this.BranchId = ko.observable(data.BranchId);
this.Name = ko.observable(data.Name);
this.Description = ko.observable(data.Description);
this.Template = ko.observable(data.Template);
this.MetaKeyword = ko.observable(data.MetaKeyword);
this.MetaDescription = ko.observable(data.MetaDescription);
this.MetaTitle = ko.observable(data.MetaTitle);
this.EnableSearch = ko.observable(data.EnableSearch);
}
function BranchViewModel() {
var self = this;
self.EnableSearchs = ko.observableArray(['Yes', 'No']);
self.Templates = ko.observableArray(['Template1', 'Template2']);
self.Branches = ko.observableArray([]);
self.BranchId = ko.observable();
self.Name = ko.observable();
self.Description = ko.observable();
self.MetaKeyword = ko.observable();
self.MetaDescription = ko.observable();
self.MetaTitle = ko.observable();
self.EnableSearch = ko.observable();
self.Template = ko.observable();
self.editBranch = ko.observable();
self.show = ko.observable(true);
self.showFields = ko.observable(false);
self.flag = ko.observable(false);
self.AddBranch = function () {
if (self.flag()) {
self.editBranch().BranchId(self.BranchId())
self.editBranch().Name(self.Name())
self.editBranch().Description(self.Description())
self.editBranch().EnableSearch(self.EnableSearch())
self.editBranch().MetaKeyword(self.MetaKeyword())
self.editBranch().MetaDescription(self.MetaDescription())
self.editBranch().MetaTitle(self.MetaTitle())
self.editBranch().Template(self.Template())
self.flag(false);
self.show(true);
self.showFields(false);
self.BranchId(""),
self.Name(""),
self.Description(""),
self.EnableSearch(""),
self.MetaKeyword(""),
self.MetaDescription(""),
self.MetaTitle(""),
self.Template("")
}
else{
self.Branches.push(new Branch({
BranchId: self.BranchId(),
Name: self.Name(),
Description: self.Description(),
EnableSearch: self.EnableSearch(),
MetaKeyword: self.MetaKeyword(),
MetaDescription: self.MetaDescription(),
MetaTitle: self.MetaTitle(),
Template: self.Template()
}));
self.BranchId(""),
self.Name(""),
self.Description(""),
self.EnableSearch(""),
self.MetaKeyword(""),
self.MetaDescription(""),
self.MetaTitle(""),
self.Template("")
self.show(true);
self.showFields(false);
}
};
self.AddField = function(){
self.show(false);
self.showFields(true);
}
self.DeleteBranch = function (branch) {
alert(ko.toJSON({ data: branch }));
};
self.edit = function (branch) {
self.editBranch(branch);
self.show(false);
self.showFields(true);
self.BranchId(branch.BranchId());
self.Name(branch.Name());
self.Description(branch.Description());
self.EnableSearch(branch.EnableSearch());
self.MetaKeyword(branch.MetaKeyword());
self.MetaDescription(branch.MetaDescription());
self.MetaTitle(branch.MetaTitle());
self.Template(branch.Template());
self.flag(true);
}
self.SaveBranch = function (branch) {
alert(ko.toJSON( self.Branches));
};
}
$(document).ready(function () {
ko.applyBindings(new BranchViewModel());
});
</script>
</html>
secondly i want to display some json data on my page as my page get load. here is my json data.
[{"BranchId":"1","Name":"us","Description":"united states","Template":"Template1","MetaKeyword":"us","MetaDescription":"us","MetaTitle":"us","EnableSearch":"Yes"},{"BranchId":"2","Name":"europe","Description":"europe","Template":"Template1","MetaKeyword":"euro","MetaDescription":"euro","MetaTitle":"euro","EnableSearch":"Yes"},{"BranchId":"3","Name":"aus","Description":"aus","Template":"Template1","MetaKeyword":"aus","MetaDescription":"aus","MetaTitle":"aus","EnableSearch":"Yes"}]

Here's how you do it.. You need to convert each object from json to Branch. You can use computed for that.
Create new var for the JSON dataset
var dummyData = [{"BranchId":"1","Name":"us","Description":"united states","Template":"Template1","MetaKeyword":"us","MetaDescription":"us","MetaTitle":"us","EnableSearch":"Yes"},{"BranchId":"2","Name":"europe","Description":"europe","Template":"Template1","MetaKeyword":"euro","MetaDescription":"euro","MetaTitle":"euro","EnableSearch":"Yes"},{"BranchId":"3","Name":"aus","Description":"aus","Template":"Template1","MetaKeyword":"aus","MetaDescription":"aus","MetaTitle":"aus","EnableSearch":"Yes"}];
self.PopulateBranches = ko.computed(function(){
ko.utils.arrayForEach(dummyData, function(item){
self.Branches.push(new Branch(item));
});
});
Here's updated JSFiddle for you : http://jsfiddle.net/x2ubuy44/

Related

multiple search from one entry

I populate this table from an API and try to do a multiple lookup filter from one entry separating each entry by a comma.
they load the data correctly but when trying to search it does nothing
Is this code any good or how could I do a multiple search from one input?
View
File ApiControllers.js
<script>
var testApp = angular.module("LogModule", []);
testApp.controller("TransController", function ($scope, $http) {
$http.get('/api/Trans').then(function (response) {
$scope.logTrans = response.data;
$scope.Show = [];
$scope.separator = ""
$scope.buscar = function () {
let search = $scope.separator.split(",");
$scope.Show =
$scope.logTrans
.filter((item) => {
let a = search.map((value) => {
return JSON.stringify(item)
.toUpperCase()
.indexOf(value.toUpperCase()) > -1 ? 1 : 0;
}).reduce((x, y) => x + y);
return a > 0
})
}
$scope.searchInput()
});
});
File html
<!DOCTYPE html>
<html ng-app="LogModule">
<head>
<script src="~/Scripts/angular.js"></script>
<script src="~/Scripts/ApiCotrollers.js"></script>
<link />
</head>
<body>
<h1>Consulta de transacciones</h1>
<div ng-app="LogModule" class="table-responsive" ng-controller="TransController">
<input type="text" ng-model="filter" ng-change="searchInput()" class="form-control" placeholder="Buscar documentos" aria-describedby="basic-addon2 ">
<br>
<table class="table table-bordered table-hover" align="center">
<tr class="active">
<th> Registro</th>
<th> FechaInsert</th>
<th> FechaModificacion</th>
<th>Observaciones</th>
<th> IdIntegracion</th>
<th>Integrado</th>
<th> Error</th>
<th>ObjetoIntegracion</th>
<th> Bodega</th>
</tr>
<tr ng-repeat=" p in Show track by $index">
<td class="success"> {{p.Registro}}</td>
<td class="success"> {{p.FechaInsert}} </td>
<td class="success"> {{p.FechaModificacion}} </td>
<td class="danger"> {{p.Observaciones}} </td>
<td class="success">{{p.IdIntegracion}} </td>
<td class="success"> {{p.Integrado}} </td>
<td class="success"> {{p.Error}} </td>
<td class="danger"> {{p.ObjetoIntegracion}}</td>
<td class="success">{{p.Bodega}}</td>
</tr>
</table>
</div>
#Scripts.Render("~/bundles/jquery")
#Scripts.Render("~/bundles/bootstrap")
</body>
</html>

How do i submit my angular form?

I have my edit page and i would like to submit info to db once fields have been edited, it seems like something simple yet i cannot find a good example that pertains to my situation, i really don't know how to go about resolving this, this is the last part of my project. I would appreciate any suggestions Please.
This is my edit page code:
<title>
</title>
</head>
<body ng-app="app" ng-controller="decontroller" class="container">
<div id="banner" style="text-align:center; margin-left:auto; margin- right:auto; display:block;">
</div>
<h2></h2>
<h3>Personal Information:</h3>
<div id="validation-errors">
</div>
<form action="" method="post" accept-charset="utf-8" ng-submit="addEdit()">
<table class="table table-bordered">
<tbody>
<tr>
<td>ParticipantID</td>
<td>{{edit.Stlc_id}}</td>
</tr>
<tr>
<td>First Name:<br>
</td>
<td>{{edit.First_Name}}</td>
</tr>
<tr>
<td>Last Name:<br>
</td>
<td>{{edit.Last_Name}}</td>
</tr>
<tr>
<td>Address:</td>
<td><input type="text" name ="Address" ng-model="edit.Address" ></td>
</tr>
<tr>
<td>Phone:</td>
<td><input size="20" name ="phone" ng-model="edit.Phone_Number" ></td>
</tr>
<tr>
<td>Assistive Devices:</td>
<td><input name ="AssistiveDevices" ng-model="edit.Assistive_Devices" ></td>
</tr>
<tr>
<td>Lanyard Code</td>
<td>
<input name ="Lanyard_Status" ng-model="edit.Lanyard_Status" /> </td>
</tr>
<tr>
<td>Comments</td>
<td>
<textarea cols="100" name="comments" ng-model="edit.Comments">.</textarea>
</td>
</tr>
<tr>
<td>Disenrolled</td>
<td><input name="disenrolled" ng-model="edit.Disenrolled" ></td>
</tr>
<tr>
<td>Deceased</td>
<td><input name="deceased" ng-model="edit.Deceased" ></td>
</tr>
</tbody>
</table>
</form>
<h3>Days in Center<br></h3>
<table class="table table-bordered">
<tbody>
<tr>
<td>Monday</td>
<td>Tuesday</td>
<td>Wednesday</td>
<td>Thursday</td>
<td>Friday</td>
</tr>
<tr>
<td><input name="Attendance_Monday" ng-model="edit.Attendance_Monday" ></td>
<td><input name="Attendance_Tuesday" ng-model="edit.Attendance_Tuesday" ></td>
<td><input name="Attendance_Wednesday" ng-model="edit.Attendance_Wednesday" ></td>
<td><input name="Attendance_Thursday" ng-model="edit.Attendance_Thursday" ></td>
<td><input name="Attendance_Friday" ng-model="edit.Attendance_Friday" > </td>
</tr>
</tbody>
</table>
<h3>Transportation Types</h3>
<table class="table table-bordered">
<tr>
<td>Type of Transportation</td>
<td>Approved For</td>
<td>Comments</td>
</tr>
<tr>
<td width="300px">Wheel Chair Van</td>
<td><input name="WheelChair_Van" ng-model="edit.WheelChair_Van"></td>
<td><textarea cols="100" name="WheelChair_Van comments" ng-model="edit.Comments" ></textarea></td>
</tr>
<tr>
<td width="300px">Transit Van 240</td>
<td><input name="TransitVan_240" ng-model="edit.TransitVan_240"></td>
<td><textarea cols="100" name="TransitVan_240 comments" ng-model="edit.Comments" ></textarea></td>
</tr>
<tr>
<td width="300px">Transit Van 360</td>
<td><input name="TransitVan_360" ng-model="edit.TransitVan_360"></td>
<td><textarea cols="100" name="TransitVan_360 comments" ng- model="edit.Comments"></textarea></td>
</tr>
<tr>
<td width="300px">Subaru Impreza</td>
<td><input name="Subaru_Impreza" ng-model="edit.Subaru_Impreza"></td>
<td><textarea cols="100" name="Subaru_Impreza comments" ng- model="edit.Comments"></textarea></td>
</tr>
</table>
<h3>Pick up and Drop Off Times</h3>
<br>
<table class="table table-bordered">
<tr>
<td width="300px">Pick Up Time:</td><td><input type="text" name="Pick_Up_Time" value=""></td>
</tr>
<tr>
<td width="300px">Drop off Time</td><td><input type="text" name="Drop_Off_Time" value=""></td>
</tr>
</table>
<br>
<h3>Personal Care Hours Pick Up/Drop Off</h3>
<table class="table table-bordered">
<tbody>
<tr>
<td>Monday</td>
<td>Tuesday</td>
<td>Wednesday</td>
<td>Thursday</td>
<td>Friday</td>
<td>Saturday</td>
<td>Sunday</td>
</tr>
<tr>
<td><input type="text" name="Monday_Pick_Up" ng-model="edit.Monday_Pick_Up" placeholder="Pick Up Time"></td>
<td><input type="text" name="Tuesday_Pick_Up" ng-model="edit.Tuesday_Pick_Up" placeholder="Pick Up Time"></td>
<td><input type="text" name="Wednesday_Pick_Up" ng-model="edit.Wednesday_Pick_Up" placeholder="Pick Up Time"></td>
<td><input type="text" name="Thursday_Pick_Up" ng-model="edit.Thursday_Pick_Up" placeholder="Pick Up Time"></td>
<td><input type="text" name="Friday_Pick_Up" ng-model="edit.Friday_Pick_Up" placeholder="Pick Up Time"></td>
<td><input type="text" name="Saturday_Pick_Up" ng-model="edit.Saturday_Pick_Up" placeholder="Pick Up Time"></td>
<td><input type="text" name="Sunday_Pick_Up" ng-model="edit.Sunday_Pick_Up" placeholder="Pick Up Time"></td>
</tr>
<tr>
<td><input type="text" name="Monday_Drop_Off" ng-model="edit.Monday_Drop_Off" placeholder="Drop Off Time"></td>
<td><input type="text" name="Tuesday_Drop_Off" ng-model="edit.Tuesday_Drop_Off" placeholder="Drop Off Time"></td>
<td><input type="text" name="Wednesday_Drop_Off" ng-model="edit.Wednesday_Drop_Off" placeholder="Drop Off Time"></td>
<td><input type="text" name="Thursday_Drop_Off" ng-model="edit.Thursday_Drop_Off" placeholder="Drop Off Time"></td>
<td><input type="text" name="Friday_Drop_Off" ng-model="edit.Friday_Drop_Off" placeholder="Drop Off Time"></td>
<td><input type="text" name="Saturday_Drop_Off" ng-model="edit.Saturday_Drop_Off" placeholder="Drop Off Time"></td>
<td><input type="text" name="Sunday_Drop_Off" ng-model="edit.Sunday_Drop_Off" placeholder="Drop Off Time"></td>
</tr>
</tbody>
</table>
<input type="submit" name="submit" ng-click="saveEdit()" />
</form>
<pre>{{edit | json}}</pre>
<a href="http://localhost:8080/stlc/index.php/transport/list_show_data/transport_vi ew">
<button type="button" class="btn btn-primary">Back</button>
</a>
<script src="http://code.jquery.com/jquery-3.1.1.min.js"></script>
<script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/angularjs/1.5.8/angular.min.js"> </script>
<script type="text/javascript">
var app = angular.module('app',[]);
app.controller('decontroller', function($scope,$http){
$scope.edit=<?php echo json_encode($aggregate_data_view);?>;
$scope.saveEdit = function(){
console.log("hey i'm submitting!");
console.log($scope.edit);
$http.post('?php echo site_url("index.php/transport/saveData")?>', $scope.edit).
success(function(data){console.log(":)") }).
error(function(data){
console.log(":(")
});
};
});
</script>
</body>
</html>
Here is my Controller:
public function saveData()
{
}
it is empty now cause i really don't know what to do,nothing has worked.
In my page I have three button. First two create random AVL data on the page
the second one save that data to the db
HTML:
<button data-ng-click="createAvl()">Create Avl</button>
<button data-ng-click="create1000Avl()">Create 1000 Avl</button>
<button data-ng-click="saveAvl()">Save Avl</button>
ngController:
app.controller("myCtrl", function ($scope, $http) {
$scope.avl = []; --here is where i save the avl
$scope.avl.push({
'tracker_avl_id': getRandomArbitrary(0, 1000000, 1),
'plate_num': getRandomArbitrary(0, 10000, 1),
'x_lat': getRandomArbitrary(-69, -66, 0),
'y_long': getRandomArbitrary(8, 10, 0),
'azimuth': getRandomArbitrary(0, 359, 1),
'engine_status': engine,
'gps_fix': gps_fix,
'event_time': getRandomDate()
});
$scope.saveAvl = function () {
$scope.ResponseDetails = 'Working...'; -- some variables to show progress
$scope.startDate = getDate();
$scope.startTime = new Date().getTime();
$scope.timeEllapsed = null;
-- use $.param jQuery function to serialize data from JSON
var data = $.param({
avl_list: $scope.avl
});
var config = {
headers: {
'Content-Type': 'application/x-www-form-urlencoded;charset=utf-8;'
}
}
-- send the data to my webservice
$http.post('/AvlApi/putTrackerAVL', data, config)
.success(function (data, status, headers, config) {
var end = new Date().getTime() - $scope.startTime;
$scope.timeEllapsed = 'milliseconds passed: ' + end;
$scope.ResponseDetails = data;
})
.error(function (data, status, header, config) {
$scope.ResponseDetails = "Data: " + data +
"<hr />status: " + status +
"<hr />headers: " + header +
"<hr />config: " + config;
});
};
My Webservice is in IIS using C#
[HttpPost]
public JsonResult putTrackerAVL(List<avl> avl_list)
{
try
{
avl_list.ForEach(car => db.avl.Add(car));
db.SaveChanges();
}
catch (Exception ex)
{
return Json(new { status = "Fail", message = ex.InnerException });
}
return Json(new { status = "Success" });
}

Knockout: Can't push to observableArray

I've recently started using KnockOut, so I'm very new to this.
I have completed every tutorial on their site, yet can't get this specific thing to work.
I have to arrays, on the left being all the items, on the right being the items you've selected.
Once you click on the item (left table), it should .push to the right table
ViewModel:
var orderedItemsTable = $("form.orderedDataWithoutBatch")
var viewModel = {
//right side
orderedItems: ko.observableArray(),
//Left side
items: ko.observableArray(),
sortColumn: ko.observable(),
total: ko.observable(),
}
request.done(function (data) {
item.addItem = function () {
alert("item clicked, materiaal id: " + this.MateriaalId);//works
alert(this.MateriaalDescription);//works
viewModel.orderedItems.push(this);//doesn't 'work'
}
viewModel.items.push(item);//unrelated to this context
}
I'm assuming it's either in this code here, or I'm not showing it correctly in my html (because I'm not getting any console errors)
HTML (right side)
<form id="OrderedItemsWithoutBatch" class="orderedDataWithoutBatch">
<table class="orderFormArticlesTable" style="width: 47%;float: right; font-size: 9pt;">
<thead>
<tr>
<th>SKU</th>
<th>Product</th>
<th style="width: 15%">Qty</th>
<th></th>
</tr>
</thead>
<tbody data-bind="foreach: orderedItems">
<tr>
<td data-bind="text: MateriaalSku"> </td>
<td data-bind="text: MateriaalDescription"> </td>
<td data-bind="text: MateriaalId"><!-- Quantity--> </td>
<!--<td><input class="orderedQty" style="max-width: 15%" value="1" />[pieces]</td>-->
<td>Remove</td>
</tr>
</tbody>
</table>
I'm not sure I've understood you right, but I'd solve your task this way:
var orderedItemsTable = $("form.orderedDataWithoutBatch")
var viewModel = {
//right side
orderedItems: ko.observableArray(),
//Left side
items: ko.observableArray(),
sortColumn: ko.observable(),
total: ko.observable(),
}
function proscessRequest(item) {
item.addItem = function () {
//alert("item clicked, materiaal id: " + this.MateriaalId);//works
//alert(item.MateriaalDescription);//works
viewModel.orderedItems.push(this);//doesn't 'work'
}
viewModel.items.push(item);//unrelated to this context
}
ko.applyBindings(viewModel);
proscessRequest({MateriaalSku: "M1", MateriaalDescription: "D1", MateriaalId: "1"});
proscessRequest({MateriaalSku: "M2", MateriaalDescription: "D2", MateriaalId: "2"});
proscessRequest({MateriaalSku: "M3", MateriaalDescription: "D3", MateriaalId: "3"});
proscessRequest({MateriaalSku: "M4", MateriaalDescription: "D4", MateriaalId: "4"});
<script src="https://cdnjs.cloudflare.com/ajax/libs/knockout/3.2.0/knockout-min.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.0/jquery.min.js"></script>
<form id="OrderedItemsWithoutBatch" class="orderedDataWithoutBatch">
<div>Alavilable items:</div>
<div>
<table class="orderFormArticlesTable">
<thead>
<tr>
<th>SKU</th>
<th>Product</th>
<th style="width: 15%">Qty</th>
<th></th>
</tr>
</thead>
<tbody data-bind="foreach: items">
<tr>
<td data-bind="text: MateriaalSku"> </td>
<td data-bind="text: MateriaalDescription"> </td>
<td data-bind="text: MateriaalId"><!-- Quantity--> </td>
<td><div data-bind="click: addItem">Add</div></td>
</tr>
</tbody>
</table>
</div>
<div style="margin-top: 30px;">
<div>Ordered items:</div>
<table class="orderFormArticlesTable">
<thead>
<tr>
<th>SKU</th>
<th>Product</th>
<th style="width: 15%">Qty</th>
<th></th>
</tr>
</thead>
<tbody data-bind="foreach: orderedItems">
<tr>
<td data-bind="text: MateriaalSku"> </td>
<td data-bind="text: MateriaalDescription"> </td>
<td data-bind="text: MateriaalId"><!-- Quantity--> </td>
<td><div data-bind="click: function() { $parent.orderedItems.remove($data); }">Remove</div></td>
</tr>
</tbody>
</table>
</div>
</form>
Note
I've mocked request with "proscessRequest" function called after bindings have been applied.

Dispay data from database to textbox asp.net mvc

How will I properly display data from database to textbox when the button "search" is clicked? It should display the item name and the price of that product code
enter image description here
Controller
public ActionResult Index(string searchString)
{
using(MyDatabaseEntities db = new MyDatabaseEntities())
{
var products = from s in db.Products
select s;
if (!String.IsNullOrEmpty(searchString))
{
products = products.Where(s => s.ProductCode.Equals(searchString));
}
return View(products.ToList());
}
}
Index
<div class="form-group">
<table style="text-align:left; margin-bottom:10px;">
<tr>
<td>Item Code</td>
<td>#Html.TextBox("SearchString")
</td>
<tr style="background-color:lightgray;">
<td colspan="2"></td>
</tr>
<tr>
<td colspan="2">
<input type="submit" class="btn btn-block btn-info"id="buttonsearch" value="Search" />
</td>
</tr>
<tr>
<td> </td>
</tr>
#foreach (var item in Model) {
<tr>
<td style="text-align:left;">Item Name</td
<td>#Html.DisplayFor(modelItem=> item.ProductName)</td>
</tr>
<tr>
<td>Unit Price</td>
<td style="text-align:right;">#Html.DisplayFor(modelItem => item.Price)</td>
</tr>
}
<tr>
<td style="text-align:left;">Quantity</td>
<td>
<input type="text" id="quantity" class="input-sm" />
<span class="error">Product Name required</span>
</td>
</tr>
<tr>
<td style="text-align:left;">Discount</td>
<td>
<input type="text" id="discount" class="input-sm" style="text-align:right;" placeholder="0.00" />
<span class="error">Product Name required</span>
</td>
</tr>
</table>
</div>
Instead of .ToList() use .FirstOrDefault(); just in case you want to populate one record in your textbox.

How to clear/remove values from onblur event after the tab is changed

My problem is that in my registration form when it has error message and the user tries to changed tab and back again to registration the error message are still there what should I do to be able to remove the error message when I changed the tabs and when I click again the registration link?
<script src="http://code.jquery.com/jquery-1.8.1.js"></script>
<script>
$(function() {
var tabContainers = $('section.tabs > article');
tabContainers.hide().filter('#login').show();
$('.ultabs a').click(function () {
tabContainers.hide();
tabContainers.filter(this.hash).show();
$('.ultabs a').removeClass('selected');
$(this).addClass('selected');
return false;
});
});
function check_email() {
var email=$("#textEmail").val();
$.ajax(
{
type:"POST",
url:"register.php",
data: {
'email': email
},
success:function(msg) {
$("#checkEmail").html(msg);
}
});
return false;
}
function check_password() {
var pass=$("#textPassword").val();
$.ajax(
{
type:"POST",
url:"register.php",
data: {
'pass': pass
},
success:function(msg) {
$("#checkPassword").html(msg);
}
});
return false;
}
</script>
<nav id="siteNav">
<h1>Navigation</h1>
<ul class="ultabs">
<li>Login</li>
<li>Register</li>
</ul>
</nav>
<section id="siteContent" class="tabs">
<h1>Section</h1>
<article id="login">
<h1>Login</h1>
<table>
<tr>
<td class="message" colspan="2"></td>
</tr>
<tr>
<td>E-mail:</td><td><input type="email"></td>
</tr>
<tr>
<td class="message" colspan="2"></td>
</tr>
<tr>
<td>Password:</td><td><input type="password"></td>
</tr>
<tr>
<td colspan="2"><input type="button"></td>
</tr>
</table>
</article>
<article id="register">
<h1>Register</h1>
<table>
<tr>
<td class="message" colspan="2"></td>
</tr>
<tr>
<td>Name:</td><td><input type="text"></td>
</tr>
<tr>
<td id="checkEmail" class="message" colspan="2"></td>
</tr>
<tr>
<td>E-mail:</td><td><input id="textEmail" type="email" onblur="return check_email()"></td>
</tr>
<tr>
<td id="checkPassword" class="message" colspan="2"></td>
</tr>
<tr>
<td>Password:</td><td><input id="textPassword" type="password" onblur="return check_password()"></td>
</tr>
<tr>
<td class="message" colspan="2"></td>
</tr>
<tr>
<td>Re-type:</td><td><input type="password"></td>
</tr>
<tr>
<td colspan="2"><input type="button"></td>
</tr>
</table>
</article>
</section>
I would suggest you use a validator plugin like the one provided by Bassistance - http://bassistance.de/jquery-plugins/jquery-plugin-validation/ . It will handle the error messages without you getting into the nitty gritty of validation....
You can clear the td on change of the tab
$('.ultabs a').click(function () {
$('.message').html('');
// the rest of your code
});