Knockoutjs and binding - asp.net-mvc

I'm going crazy with knockuoutjs and binding:
I have defined a CreateEditGroup.js document and I have created methods and Collection to retrieve or update a Group in my application:
var url = window.location.pathname;
var GroupID = url.substring(url.lastIndexOf('/') + 1);
var Group = function (group)
{
var self = this;
self.GroupID = ko.observable(group ? group.GroupID : 0).extend({ required: true });
self.Name = ko.observable(group ? group.Name : '').extend({ required: true });
};
var GroupCollection = function () {
var self = this;
if (GroupID == 0) {
self.group = ko.observable(new Group());
}
else {
$.ajax({
url: '/Group/GetGroupByID/' + GroupID,
async: false,
dataType: 'json',
success: function (json) {
self.group = ko.observable(new Group(json));
}
});
}
self.backToGroupList = function () { window.location.href = '/App/Groups' };
//Aggiunta o modifica
self.saveGroup = function () {
$.ajax({
type: (self.group().GroupID > 0 ? 'PUT' : 'POST'),
cache: false,
dataType: 'json',
url: urlContact + (self.group().GroupID > 0 ? '/UpdateGroup?id=' + self.group().GroupID : '/SaveGroup'),
data: JSON.stringify(ko.toJS(self.group())),
contentType: 'application/json; charset=utf-8',
async: false,
success: function (data) {
window.location.href = '/App/Groups';
},
error: function (err) {
var err = JSON.parse(err.responseText);
var errors = "";
for (var key in err) {
if (err.hasOwnProperty(key)) {
errors += key.replace("group.", "") + " : " + err[key];
}
}
$("<div></div>").html(errors).dialog({ modal: true, title: JSON.parse(err.responseText).Message, buttons: { "Ok": function () { $(this).dialog("close"); } } }).show();
},
complete: function () {
}
});
};
};
ko.applyBindings(new GroupCollection());
And the view that shows the form have this HTML code:
#{
ViewBag.Title = "CreateEditGroup";
}
<h2>Nuovo gruppo</h2>
<table class="table">
<tr>
<th colspan="1">
</th>
</tr>
<tr></tr>
<tbody data-bind="with: Group">
<tr>
<td>
<input class="input-large" data-bind="value: Name" placeholder="Nome" />
</td>
</tr>
</tbody>
</table>
<button class="btn btn-small btn-success" data-bind="click: saveGroup">Salva</button>
<input class="btn btn-small btn-primary" type="button" value="Annulla" data-bind="click: $root.backToGroupList" />
<script src="#Url.Content("~/Repository/CreateEditGroup.js")"></script>
Everytime that I load the CreateEditGroup page I receive the message that is impossibile to bind Name attribute, but the code seems good.
Help me, please.
Code error:
An unhandled exception occurred at line 1936 column 17 in http://localhost:2297/Scripts/knockout-2.2.1.debug.js
0x800a139e - Run-time JavaScript: Unable to parse bindings.
Message: ReferenceError: 'Name' is not defined;
Bindings value: value: Name

I believe you have a capitalization error.
data-bind="with : Group"
Should be
data-bind="with : group"

I have solved this puzzle!
The error is simply: in CreateEditGroup.js I have declared a variable that have called Group and an object called group
var Group = function (group)
{
var self = this;
self.GroupID = ko.observable(gruppo ? gruppo.GroupID : 0).extend({ required: true });
self.Name = ko.observable(gruppo ? gruppo.Name : '').extend({ required: true });
};
I have modified the name of the object passed in this function with another name and finally works!
var Group = function (gruppo)
{
var self = this;
self.GroupID = ko.observable(gruppo ? gruppo.GroupID : 0).extend({ required: true });
self.Name = ko.observable(gruppo ? gruppo.Name : '').extend({ required: true });
};
Thank you all for the help!

Related

C# razor select2 disable

Is there a way I can set this select2 to be disable read-only if there is a value in option.AgentName? I have add the selectElement.select2 method is there anything I can add to the callback?
Is this the correct way to do this? using self.entry.Agent.AgentName != ""?
View
<div class="form-group sentence-part-container sentence-part ng-scope ui-draggable sentence-part-entry-agent sentence-part-with-select2-single" [class.has-errors]="entry.IsInvalid && entry.IsTouched">
<div class="sentence-part-values">
<div class="sentence-part-values-select2-single">
<select class="form-control" style="width: 300px" [(ngModel)]="entry.Agent.VersionKey">
<option *ngFor="let option of agents" [value]="option.VersionKey">{{option.AgentName}}</option>
</select>
</div>
</div>
</div>
ts file
$selectElement.select2({
initSelection: function(element, callback) {
console.log(self.entry.Agent.AgentName);
if (self.entry.Agent.AgentName != "")
{
console.log('disabled');
$selectElement.prop('disabled', true);
}
callback({ id: self.entry.Agent.VersionKey, text: self.entry.Agent.AgentName });
},
placeholder: "Select an agent"
})
.on("change", (e) => {
self.ngZone.run(() => {
self.entry.Agent.VersionKey = $selectElement.val();
self.entry.AgentVersionKey = self.entry.Agent.VersionKey;
let regimenEntryAgent = this.getRegimenEntryAgentByVersionKey(self.entry.Agent.VersionKey);
if (regimenEntryAgent) {
self.entry.Agent.AgentId = regimenEntryAgent.AgentId;
}
self.onSentenceChange(null);
});
})
.on("select2:close", () => {
self.entry.IsTouched = true;
this.validate();
});
You might try to apply some logic in newData.push() method of Select2.
ajax: {
url: '/DemoController/DemoAction',
dataType: 'json',
delay: 250,
data: function (params) {
return {
query: params.term, //search term
page: params.page
};
},
processResults: function (data, page) {
var newData = [];
$.each(data, function (index, item) {
// apply some logic to the corresponding item here
if(item.AgentName == "x"){
}
newData.push({
//id part present in data
id: item.Id,
//string to be displayed
text: item.AgentName
});
});
return { results: newData };
},
cache: true
},
Update:
It is recommended that you declare your configuration options by passing in an object when initializing Select2. However, you may also define your configuration options by using the HTML5 data-* attributes.
For the other Select2 options look Options.

Select2 initSelection element Val

I am using the select2 control on my web aplciation. In the initSelection I am passing the element.val() to a controller but it is null. How would I set element.val() that i want pass to the Url.Action. Is element.val() the correct object that I should be using when I am using a div?
I see the value in Chrome
debugger
view
<div id="guideline-container" style="#(Model.Type == "Guideline" ? "display:block" : "display:none")">
<form id="guideline-form" class="form-horizontal">
<div class="form-group">
<label for="guidelineName" class="col-sm-2 control-label">Guideline</label>
<div class="col-sm-10">
<div id="guidelineName">
#{ Html.RenderAction("Index", "GuidelinesPicklist", new { value = Model.GuidelineId, leaveOutAlgorithmItems = true, separateActiveItems = true }); }
</div>
<div class="guideline-not-selected field-validation-error" style="display: none;">
Guideline is required.
</div>
</div>
</div>
<div class="text-center">
<button type="submit" class="btn btn-primary modal-submit-btn">Add</button>
<button type="button" class="btn btn-default modal-close-btn" data-dismiss="modal">Close</button>
</div>
</form>
</div>
function
$(this).select2({
placeholder: "#Model.Settings.Placeholder",
//allowClear: true,
ajax: {
url: "#Url.Action("GetPicklistItems")",
contentType: 'application/json; charset=utf-8',
type: 'POST',
dataType: 'json',
data: function (params) {
return JSON.stringify({
query: params.term,
args: #Html.Raw(JsonConvert.SerializeObject(#Model.Settings != null ? #Model.Settings.AdditionalArguments : null))
});
},
processResults: function (data, page) {
console.log("processResults");
console.log(data);
var resultData = [];
if (isError(data)) {
showErrorMessage(getErrorMessage(data));
} else {
hideErrorMessage();
mapResultData(data.Result, resultData, 0);
}
return {
results: resultData
};
}
},
templateResult: format,
templateSelection: function(data) {
return data.text;
},
initSelection: function (element, callback) {
//console.log("initSelection");
//var id = $(element).val();
//console.log(id);
var guidelineId = "#Model.Value";
console.log("guidelineId");
console.log(guidelineId);
//console.log("params");
//console.log(params);
//console.log("element object Text");
//console.log(element.text);
debugger;
getAjax("#Url.Action("GetPicklistItem")" + "?value=" + guidelineId, function (result)
{
console.log("Ajax GetPicklistItem");
console.log(result);
debugger;
if (result.Result) {
var data = {};
$.extend(data, result.Result);
data.id = result.Result.Value;
data.text = result.Result.Text;
callback(data);
self.trigger("picklistChanged", data);
} else {
console.log(result);
debugger;
callback ({ id: null, text: "#Model.Settings.Placeholder" })
}
});
},
escapeMarkup: function(m) {
return m;
}
}).on('change', function () {
var data = self.select2('data');
self.trigger("picklistChanged", data);
});
You can get Select2 selected value or text by using the following approaches:
var selectedValue = $('#Employee').val();
var selectedText = $('#Employee :selected').text();
Alternatively you can simply listen to the select2:select event to get the selected item:
$("#Employee").on('select2:select', onSelect)
function onSelect(evt) {
console.log($(this).val());
}

Add Text Search to Kendo Grid

I am trying out the open source Kendo Grid for the first time. I have the basic grid up and running just fine, but now I need to add a search feature, with a search on first and last names. I am trying to do it in ajax but I am stuck on an error:
Error: Cannot call method 'read' of undefined
my code:
<div id="search-index">
<div class="editor-field">
<label>First Name:</label>
#Html.TextBox("FirstName")
<label style = "margin-left: 15px;">Last Name:</label>
#Html.TextBox("LastName", "", new { style = "margin-right: 15px;" })
</div>
<div id="search-controls-index">
<input type="button" id="searchbtn" class="skbutton" value="Search" />
<input type="button" id="addPersonbtn" class="skbutton" value="Add New Person" onclick="location.href='#Url.Action("AddPerson", "Person")'"/>
</div>
</div>
<div id="index-grid"></div>
</div>
$(document).ready(function () {
var grid = $('#index-grid').kendoGrid({
height: 370,
sortable: true,
scrollable: true,
pageable: true,
dataSource: {
pageSize: 8,
transport: {
read: "/Home/GetPeople",
dataType:"json"
}
},
columns: [
{ field: "FirstName", title: "First Name" },
{ field: "LastName", title: "Last Name" },
{ field: "Gender", title: "Gender" },
{ field: "DOB", title: "Date of Birth", template: '#= kendo.toString(new Date(parseInt(DOB.substring(6))), "MM/dd/yyyy") #' },
{ field: "IsStudent", title: "Is a Student?" }]
});
$("#searchbtn").on('click', function () {
var fsname = $("#FirstName").val();
var ltname = $("#LastName").val();
$.ajax({
type: 'GET',
url: '#Url.Content("~/Home/GetPeople")',
data: { fname: fsname, lname: ltname },
success: function (data) {
grid.dataSource.read();
},
error: function () {
$("#index-grid").html("An error occured while trying to retieve your data.");
}
});
});
});
Should matter, but here is my controller (using asp MVC 3):
public JsonResult GetPeople(string fname, string lname)
{
if (((fname == "") && (lname == "")) || ((fname == null) && (lname == null)))
{
var peopleList = repo.GetPeople();
return Json(peopleList, JsonRequestBehavior.AllowGet);
}
else
{
var personResult = repo.GetSearchResult(fname, lname);
return Json(personResult, JsonRequestBehavior.AllowGet);
}
}
The problem is that $("#grid").kendoGrid() returns a jQuery object which doesn't have a dataSource field. Here is how to get a reference to the client-side object: http://docs.kendoui.com/getting-started/web/grid/overview#accessing-an-existing-grid

How to stop explorer Json downloading strange bahaviour?

i can not bind Json data to table. Also internet explorer wants to download Json data. How to stop explorer download request and fill table. i have been reading more stackoverflow questions and googling articles. i can not understand why knockout.js cannot bind data. i have been learned binding arhitecture in knockout and json binding.
like That:
http://jsfiddle.net/madcapnmckay/3rRUQ/1/
http://jsfiddle.net/rniemeyer/5EWDG/
i would like to use binding theese methods. but i can not stopping iexplorer downloading behavior.
var result = function () {
$.ajax({
type: "get",
url: "/Contact/GetEmployees/",
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (data) {
viewModel = ko.mapping.fromJS(data, self.Employees);
},
error: function (error) {
alert(error.status + "<--and--> " + error.statusText);
}
});
};
ko.utils.arrayMap(result, function (i) { Directory.list.push(new Employee(i.EmployeeCode, i.EmployeeName)); });
also :
#{
ViewBag.Title = "GetPerson";
Layout = "~/Views/Shared/_Layout.cshtml";
}
<h2>GetPerson</h2>
<script type="text/javascript">
function Person(FirstName, LastName, Friends) {
var self = this;
self.FirstName = ko.observable(FirstName);
self.LastName = ko.observable(LastName);
self.FullName = ko.computed(function () {
return self.FirstName() + ' ' + self.LastName();
})
self.Friends = ko.observableArray(Friends);
self.AddFriend = function () {
self.Friends.push(new Person('new', 'friend'));
};
self.DeleteFriend = function (friend) {
self.Friends.remove(friend);
};
}
var viewModel = new Person();
$(document).ready(function () {
$.ajax({
url: 'Person/GetPerson',
dataType: 'json',
type: 'GET',
success: function (jsonResult) {
viewModel = ko.mapping.fromJS(jsonResult, mapping);
console.log(viewModel);
ko.applyBindings(viewModel);
}
});
});
var mapping = {
create: function (options) {
var person = options.data,
friends = ko.utils.arrayMap(person.Friends, function (friend) {
return new Person(friend.FirstName, friend.LastName);
});
return new Person(person.FirstName, person.LastName, friends);
}
};
</script>
#using (Html.BeginForm())
{
<p>First name: <input data-bind="value: FirstName" /></p>
<p>Last name: <input data-bind="value: LastName" /></p>
<p>Full name: <span data-bind="text: FullName" /></p>
<p>#Friends: <span data-bind="text: Friends().length" /></p>
#*Allow maximum of 5 friends*#
<p><button data-bind="click: AddFriend, text:'add new friend', enable:Friends().length < 5" /></p>
#*define how friends should be rendered*#
<table data-bind="foreach: Friends">
<tr>
<td>First name: <input data-bind="value: FirstName" /></td>
<td>Last name: <input data-bind="value: LastName" /></td>
<td>Full name: <span data-bind="text: FullName" /></td>
<td><button data-bind="click: function(){ $parent.DeleteFriend($data) }, text:'delete'"/></td>
</tr>
</table>
}
Controller Method:
public class PersonController : Controller
{
//
// GET: /Person/
public ActionResult GetPerson()
{
Person person = new Person
{
FirstName = "My",
LastName = "Name",
Friends = new List<Person>
{
new Person{FirstName = "Friend", LastName="Number1"},
new Person{FirstName = "Friend", LastName="Number2"}
}
};
return Json(person, "text/html", JsonRequestBehavior.AllowGet);
//return Json(person, JsonRequestBehavior.AllowGet); Not working
}
}
How to solve binding and downloading problem?

load data from db knockoutjs + mv3

attached the file EXAMPLE: http://jsfiddle.net/brux88/9fzG4/1/
hi,
I'm starting to use knockoutjs in an asp.net mvc project.
i have a view :
<button data-bind='click: load'>Load</button>
<table>
<thead>
<tr>
<th>Cliente</th>
<th>Colli</th>
<th>Tara</th>
<th>Peso Tara</th>
<th> </th>
</tr>
</thead>
<tbody data-bind='foreach: righe'>
<tr>
<td>
<select data-bind="
value: selectedCli,
options: clienteList,
optionsText: function(item) { return item.Rscli + '-' + item.Codcli },
optionsCaption: '--Seleziona un Cliente--'"
style=" width: 150px">
</select>
</td>
<td >
<input data-bind='value: Ncolli' />
</td>
<td>
<select data-bind="value: selectedTara,
options: taraList,
optionsText: function(item) { return item.Destara +
'-' + item.Codtara},
optionsCaption: '--Seleziona un Cliente--'"
style=" width: 150px">
</select>
</td>
<td >
<input data-bind="value: Ptara" />
</td>
<td>
<a href='#' data-bind='click: $parent.rimuoviRiga'>Elimina</a>
</td>
</tr>
</tbody>
</table>
<button data-bind='click: aggiungiRiga'>Aggiungi</button>
<button data-bind='click: salva'>Salva</button>
<button data-bind='click: annulla'>Annulla</button>​
my result from data db:
[{"Codcli":4,"Rscli":"antonio","Codtart":"1002","Despar":"ciliegino","Ncolli":10,"Pcolli":100,"Codtara":"03","Destara":"","Ptara":82,"Pnetto":18,"Prezzo":1},{"Codcli":1,"Rscli":"bruno","Codtart":"1001","Despar":"pomodoro","Ncolli":10,"Pcolli":100,"Codtara":"03","Destara":"","Ptara":10,"Pnetto":90,"Prezzo":1}]
my viewmodel knockoutjs:
<script type="text/javascript">
var listCli= [{Codcli: 1,Rscli: "Bruno"},{Codcli: 2,Rscli: "Pippo"},{Codcli: 3,Rscli: "Giacomo"}];
var listTa= [{Codtara: 01,Destara: "Plastica",Pertara:4},{Codtara: 02,Destara: "Legno",Pertara:6},{Codtara: 03,Destara: "Ploto",Pertara:8}];
var mydataserver = [{"Codcli":3,"Rscli":"Giacomo","Ncolli":10,"Codtara":"03","Destara":"Legno","Ptara":82},{"Codcli":1,"Rscli":"Bruno","Ncolli":10,"Codtara":"02","Destara":"Plastica","Ptara":10}];
var RigaOrdine = function () {
var self = this;
self.selectedCli = ko.observable();
self.clienteList = ko.observableArray(listCli);
self.Ncolli = ko.observable();
self.selectedTara = ko.observable();
self.taraList = ko.observableArray(listTa);
self.Ptara = ko.observable();
self.Ncolli.subscribe(function () {
self.Ptara(self.Ncolli() ? self.selectedTara().Pertara * self.Ncolli() : 0);
});
self.selectedTara.subscribe(function () {
self.Ptara(self.Ncolli() ? self.selectedTara().Pertara * self.Ncolli() : self.selectedTara().Pertara);
});
};
var Ordine = function () {
var self = this;
self.righe = ko.observableArray([new RigaOrdine()]); // Put one line in by default
// Operations
self.aggiungiRiga = function () {
self.righe.push(new RigaOrdine());
};
self.rimuoviRiga = function (riga) {
self.righe.remove(riga);
};
self.salva = function() {
var righe = $.map(self.righe(), function (riga) {
return riga.selectedCli() ? {
Codcli: riga.selectedCli().Codcli,
Rscli: riga.selectedCli().Rscli,
Ncolli: riga.Ncolli(),
Codtara: riga.selectedTara().Codtara,
Ptara: riga.Ptara(),
} : undefined;
});
alert( ko.toJSON(righe));
//save to server
/* $.ajax({
url: "/echo/json/",
type: "POST",
data: ko.toJSON(righe),
dataType: "json",
contentType: "application/json; charset=utf-8",
success: function(data) {
}
});*/
self.righe([new RigaOrdine()]);
};
//load from server
self.load = function() {
$.ajax({ url: '/echo/json/',
accepts: "application/json",
cache: false,
statusCode: {
200: function (data) {
alert(ko.toJSON(mydataserver));
//i do not know apply to viewmodel
},
401: function (jqXHR, textStatus, errorThrown) {
alert('401: Unauthenticated');
// self.location = "../../Account/Login.html?returnURL=/Index.html";
}
}
});
};
self.annulla = function() {
self.righe([new RigaOrdine()]);
};
};
var viewmodel = new Ordine();
ko.applyBindings(viewmodel);
​
</script>
if I want to load data from a db, how do I? Whereas there are dropdownlist
Your question is a bit weak so I will give you a more general answer.
To answer your question regarding how to load data from a db, it looks like that you have started on the right track. Usually you use an AJAX request to do the async request of data. To do this, knockoutJS provides the following function:
$.getJSON("/some/url", function(data) {
// Now use this data to update your view models,
// and Knockout will update your UI automatically
})
Source: http://knockoutjs.com/documentation/json-data.html
In the callback provided you will have access to the data returned from the server. It depends on the logic of your application what you want to do here - for some applications it might make sence to update the state of the viewmodel to make corresponding updates in the view.
If your question is more specific, please elaborate. Otherwise, I hope I got you on the right track.
As i can see.. you may want some good pratice to load.
I'll share with you mine.
Well.. return a Json as an JsonResult.
// POST: /Client/LoadClient
[HttpPost]
public JsonResult LoadClient(int? id)
{
if (id == null) return null;
var client = _business.FindById((int) id);
return Json(
new
{
id = cliente.id,
name = cliente.name,
list = cliente.listOfSomething.Select(s => new {idItemFromList = s.idWhatever, nameItemFromList = s.nameWhatever})
});
}
JS
viewmodel.Client.prototype.LoadClient= function (id) {
var self = this;
if (id == 0) {
return null;
}
$.ajax({
url: actionURL("LoadClient", "Client"),
data: { id: parseInt(id) },
dataType: "json",
success: function (result) {
if (result != null)
self.Load(result);
}
});
Load method.
viewmodel.Client.prototype.Load = function (result) {
var self = this;
self.idClient(result.id);
self.nameCliente(result.name);
self.ListOfSomething(result.list);
};
and..
ko.applyBinding(yourModel);
as u can see I'm using prototype it's a good practice too.

Resources