Cannot bind knockoutjs with mvc view - asp.net-mvc-4

I am new in knockoutjs, i am trying to bind the view, but cannot. Data from server is fetching fine, ajax is working fine, but not binding issue.
Here is my js code:
var UserViewModel = function () {
var self = this;
//Declare observable which will be bind with UI
self.Id = ko.observable("0");
self.FirstName = ko.observable("");
self.LastName = ko.observable("");
//The Object which stored data entered in the observables
var UserData = {
Id: self.Id || 0,
FirstName: self.FirstName || '',
LastName: self.LastName || ''
};
//Declare an ObservableArray for Storing the JSON Response
self.Users = ko.observableArray([]);
GetUser(12); //This is server side method.
function GetUser(userId) {
//Ajax Call Get All Employee Records
$.ajax({
type: "GET",
url: "/api/Users/" + userId,
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (response) {
//alert("success");
UserData = response.data.UserData;
alert(UserData.FirstName); //This is showing me correct name.
self.Users(response.data.UserData); //Put the response in ObservableArray
},
error: function (error) {
alert(error.status);
}
});
//Ends Here
}
}
ko.applyBindings(new UserViewModel());
Here is my view:
<form class="form-horizontal" data-bind="with: UserData">
<div class="row">
<div class="control-group">
<label class="control-label">First Name</label>
<label class="control-label" data-bind="text: FirstName"></label>
</div>
</div>
<div class="row">
<div class="control-group">
<label class="control-label">Last Name</label>
<input type="text" placeholder="Last Name" data-bind="value: LastName">
</div>
</div>

Your problem is that you are trying to two-way data-bind against a non-observable property, so when you update it it isn't notifying the UI. Make your user an observable and set it to an instance of an object or create a model to derive your properties from.
function userModel(user) {
var self = this;
self.Id = ko.observable(user.Id);
self.FirstName = ko.observable(user.FirstName);
self.LastName = ko.observable(user.LastName);
}
var viewModel = function () {
var self = this;
//The Object which stored data entered in the observables
var UserData = ko.observable();
GetUser(12);
function GetUser(userId) {
//Ajax Call Get All Employee Records
$.ajax({
type: "GET",
url: "/api/Users/" + userId,
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (response) {
//alert("success");
UserData(new userModel(response.data.UserData));
alert(UserData().FirstName()); //This is showing me correct name.
self.Users.push(UserData()); //Put the response in ObservableArray
},
error: function (error) {
alert(error.status);
}
});
}
}
ko.applyBindings(new viewModel());

Here, take from the following fiddle ::
http://jsfiddle.net/9ZCBw/
where you have a container model which owns the collection of users and has the function (ajax stripped for usability under fiddle)
function ViewModel () {
var self = this;
self.Users = ko.observableArray();
self.GetUser = function (userId) {
var UserData = {
Id: userId,
FirstName: 'Bob',
LastName: 'Ross'
};
self.Users.push(new UserModel(UserData));
}
}
Here, you have instances of Users which can then be bound to you model...as also shown.

Related

ASP.NET Core - controller will not return a view

I have a problem with my controller - it doesn't return a view. I am sending some data to the same controller, creating a new object with this data and I would like to send this object to the Create view but for some kind of reason I am staying on the same page.
View name: Create.cshtml
Controller name: ReservationController
Here is my controller action:
public IActionResult Create(int selectedTime, string selectedDate, int selectedRoomId)
{
TimeSpan time = TimeSpan.Parse($"{selectedTime}:00:00");
DateTime date = DateTime.ParseExact(selectedDate, "MM/dd/yyyy", System.Globalization.CultureInfo.InvariantCulture);
DateTime combine = date + time;
Reservation reservation = new Reservation();
reservation.RoomId = selectedRoomId;
reservation.ReservationTime = combine;
return View(reservation);
}
And my view:
#model Escape.Models.Reservation
#{
ViewBag.Title = "title";
}
<h2>My create reservation view</h2>
This is the original view I am coming from:
#using Escape.Controllers
#model Escape.Models.Room
#{
ViewData["Title"] = "Details";
}
<h4 class="title">Booking for room: #Model.Name</h4>
<div>
<p>#Model.Description</p>
<a class="btn btn-link" asp-action="Index">Back to all rooms</a>
<hr />
</div>
<div>
<input id="datepicker" type="text" name="datepicker"
onchange="onDateChange(#Model.Id)" />
</div>
<div>
<div id="displayTimes"></div>
<a id="btn-create" class="btn btn-sm"></a>
</div>
#section Scripts {
<script>
var dateToday = new Date();
$(function () {
$("#datepicker").datepicker({
minDate: dateToday
});
});
</script>
}
Ajax function on my btn-create:
function onButtonClick(val, date, room) {
var btnBack = document.getElementById("btn-create");
btnBack.innerHTML = "Create reservation";
$(btnBack).addClass('btn-outline-primary');
btnBack.addEventListener("click",
function () {
$.ajax({
type: "GET",
data: { selectedTime: val, selectedDate: date, selectedRoomId: room },
url: "/Reservation/Create",
contentType: "application/json",
dataType: "json"
});
});
}
If the link <a id="btn-create" class="btn btn-sm"></a> is supposed to make a call to the Create method of the ReservationController, then it is incomplete, and this is what you would need to change it to:
<a asp-controller="Reservation"
asp-action="Create"
id="btn-create" class="btn btn-sm">Create</a>
Update:
Your click handler does seem to send a request to the Controller, but nothing happens after that request, and the response (which contains the HTML from the View) is discarded.
Since you want to show the HTML, maybe you shouldn't even be using AJAX, and use my original answer above instead.
If for some reason you need the AJAX, then you need to create a success handler that displays the HTML:
btnBack.addEventListener("click",
function () {
$.ajax({
type: "GET",
data: { selectedTime: val, selectedDate: date, selectedRoomId: room },
url: "/Reservation/Create",
contentType: "application/json",
dataType: "json",
success: function (data) {
// ... put processing here
}
});
}
);

Loading Remote Data in Select2

I am using Select2's Loading Remote Data Functionality.The problem is that data is not getting loaded on the dropdownlist.On keypress remote function is getting called and data is returning properly,but its not showing in dropdownlist.
HTML
<div class=" form-group col-md-4" data-url="#Url.Action("GetStudentWalkInnName")" id="WalkinnName">
<div>
<label for="txtEmployee" class=" control-label">
Name
</label>
</div>
<div>
<select class="form-control " id="ddlName"></select>
</div>
</div>
Jquery
//REGISTRATION=>INDEX.JS
$(function () {
var ddlNameUrl=$("#WalkinnName").data("url");
$("#ddlName").select2({
placeholder: "Search for Name",
minimumInputLength: 1,
ajax: { // instead of writing the function to execute the request we use Select2's convenient helper
url: ddlNameUrl,
type: "POST",
dataType: 'json',
data: function (params) {
return {
term: params.term, // search term
page: params.page
};
},
processResults: function (data, params) {
params.page = params.page || 1;
return {
results: data,
};
}
}
});
});
Controller is
public JsonResult GetStudentWalkInnName(string term)
{
try
{
var walkInnNameList = _db.StudentWalkInns
.Where(s => s.CandidateName.StartsWith(term))
.Select(x => new
{
Id=x.Id,
Text=x.CandidateName
}).ToList();
return Json(walkInnNameList, JsonRequestBehavior.AllowGet);
}
catch (Exception ex)
{
return Json("", JsonRequestBehavior.AllowGet);
}
}
Any help will be highly appreciated.
According to the documentation, the format if the data should be an array of objects with names id and name i.e. lowercase (not Id and Name).
Change you query to
var walkInnNameList = _db.StudentWalkInns
.Where(s => s.CandidateName.StartsWith(term))
.Select(x => new
{
id = x.Id,
text = x.CandidateName
}); // .ToList() should not be necessary

Switching Google reCaptcha Version 1 from 2

I have successfully designed and implemented Google reCaptcha Version 2 but now my Manager wants that to be of version 1 with numbers to be entered and validated. Is there a way to switch from later to former i.e.- from 2 to 1. I am using following library for reCaptcha:
<script src='https://www.google.com/recaptcha/api.js'></script>
Update..
To implement Captcha inside form i am using following HTML..
<form class="contact_form" action="#" method="post" name="contact_form">
<div class="frm_row">
<label id="lblmsg" />
<div class="clear">
</div>
</div>
<div class="g-recaptcha" data-sitekey="6Lduiw8TAAAAAOZRYAWFUHgFw9_ny5K4-Ti94cY9"></div>
<div class="login-b">
<span class="button-l">
<input type="button" id="Captcha" name="Submit" value="Submit" />
</span>
<div class="clear"> </div>
</div>
</form>
As i need to get the Captcha inside the above form to Validate and get the response on button click but as now i am using <script src="http://www.google.com/recaptcha/api/challenge?k=6Lduiw8TAAAAAOZRYAWFUHgFw9_ny5K4-Ti94cY9"></script> , so not getting the Captcha inside the form ..Please help me to get that ..Also here is the Jquery Ajax code to send the request on Server side code..
$(document).ready(function () {
alert("hii1");
$('#Captcha').click(function () {
alert("Hii2");
if ($("#g-recaptcha-response").val()) {
alert("Hii3");
var responseValue = $("#g-recaptcha-response").val();
alert(responseValue);
$.ajax({
type: 'POST',
url: 'http://localhost:64132/ValidateCaptcha',
data: JSON.stringify({ "CaptchaResponse": responseValue }),
contentType: "application/json; charset=utf-8",
dataType: 'json', // Set response datatype as JSON
success: function (data) {
console.log(data);
if (data = true) {
$("#lblmsg").text("Validation Success!!");
} else {
$("#lblmsg").text("Oops!! Validation Failed!! Please Try Again");
}
},
error: function (XMLHttpRequest, textStatus, errorThrown) {
alert("Error");
}
});
}
});
});
Please help me ..Thanks..
You have to verify the reCaptcha at "http://www.google.com/recaptcha/api/verify" on Server side.
The parameters of this are:
privatekey: Your Private Key
remoteip: User's IP Address
challenge: Value of input[name=recaptcha_response_field]
response: Value of input[name=recaptcha_challenge_field]
Therefore, you have to post them on your server-side method like this:
cshtml file:
var recaptchaResponseField=$("input[name=recaptcha_response_field]").val();
var recaptchaChallengeField=$("input[name=recaptcha_challenge_field]").val();
// ajax block
$.ajax({
url: '/api/VerifyReCaptcha/', // your Server-side method
type: 'POST',
data: {
ipAddress: '#Request.ServerVariables["REMOTE_ADDR"]',
challengeField: recaptchaChallengeField,
responseField: recaptchaResponseField
},
dataType: 'text',
success: function (data) {
// Do something
},
Since you are using .NET so an example of C# code is as follows:
cs file:
using System.Net;
using System.Collections.Specialized;
[HttpPost]
public bool VerifyReCaptcha(string ipAddress, string challengeField, string responseField)
{
string result = "";
using (WebClient client = new WebClient())
{
byte[] response =
client.UploadValues("http://www.google.com/recaptcha/api/verify", new NameValueCollection()
{
{ "privatekey", "{Your private key}" },
{ "remoteip", ipAddress },
{ "challenge", challengeField },
{ "response", responseField },
});
result = System.Text.Encoding.UTF8.GetString(response);
}
return result.StartsWith("true");
}

JqWidget tabs - dynamically add tab with ajax content

I want create a dynamic on click append data to tab but I get in the tab undefined. Could you tell me whats wrong? Not quite sure what is the case,
My js
<script type="text/javascript">
$(document).ready(function () {
// Create jqxTabs.
$('#jqxTabs').jqxTabs({ width: 580, height: 200,showCloseButtons: true });
var length = $('#jqxTabs').jqxTabs('length') + 1;
var loadPage = function (url) {
$.get(url, function (data) {
data;
// console.log( $('#content' + length ).text(data));
// console.log(data);
});
}
$('div.s span').click(function() {
var getvalue = $(this).attr('rel');
$('#jqxTabs').jqxTabs('addFirst', 'Sample title',loadPage(getvalue).text());
$('#jqxTabs').jqxTabs('ensureVisible', -1);
});
// $('#jqxTabs').on('selected', function (event) {
// var pageIndex = event.args.item + 1;
// loadPage('pages/ajax' + pageIndex + '.htm', pageIndex);
// });
});
</script>
My html
<div class="s">
<span rel="gen.php">Load</span>
</div>
<div id='jqxWidget'>
<div id='jqxTabs'>
<ul>
</ul>
</div>
</div>
So first check the right syntax for tab control:
HTML:
....
<div id='jqxTabs'>
<ul>
<li></li>
</ul>
<div></div>
</div>
Javascript:
// Create jqxTabs.
$('#jqxTabs').jqxTabs({ width: 580, height: 200, showCloseButtons: true });
$('#jqxTabs').jqxTabs("removeFirst"); //here removes the empty tab
//here the function must return the content, and the ajax must be async false for this purpose
var loadPage = function (url) {
var result = null;
$.ajax({
url: url,
type: 'get',
dataType: 'html',
async: false,
success: function(data) {
result = data;
}
});
return result;
}
$('div.s span').click(function() {
var getvalue = $(this).attr('rel');
$('#jqxTabs').jqxTabs('addFirst', 'Sample title', loadPage(getvalue));
$('#jqxTabs').jqxTabs('ensureVisible', -1);
});
For better understanding check: http://jsfiddle.net/charlesrv/h4573ykv/1/
EDIT: For the new condition, use a custom attribute so checking would be easier:
$('div.s span').click(function() {
var getvalue = $(this).attr('rel');
var opened = $(this).attr('opened');
if (!opened) {
$(this).attr('opened', true);
$('#jqxTabs').jqxTabs('addFirst', 'Sample title', loadPage(getvalue));
$('#jqxTabs').jqxTabs('ensureVisible', -1);
}
});

knockout.js binding issue when trying to refresh data

I am using knockout.js data binding. At the page load the binding works fine and data is shown on the page correctly. Then I try to push data back to the database and the push is successful. The database receives the data OK.
The problem comes when I try to reload the data upon push success. At this time the binding already happen once (at the page load). If I don't bind it again the data on the page does not refresh. If I do the binding again knockout.js issues an error "cannot bind multiple times". If I do a cleanup before rebinding I receive an error "nodeType undefined".
Can anyone tell me what I have missed here? I am using ASP.NET MVC 4.0 with knockout.js 3.0.0.
Controller:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
namespace MvcApplJSON.Controllers
{
public class KnockoutController : Controller
{
//
// GET: /Knockout/
public ActionResult Index()
{
return View();
}
[HttpGet]
public JsonResult GetProductList()
{
var model = new List<Product>();
try
{
using (var db = new KOEntities())
{
var product = from p in db.Products orderby p.Name select p;
model = product.ToList();
}
}
catch (Exception ex)
{ throw ex; }
return Json(model, JsonRequestBehavior.AllowGet);
}
// your controller action should return a JsonResult. There's no such thing as a controller action that returns void. You have specified dataType: 'json' so return JSON. That's it. As far as what parameter this controller action should take, well, from the JSON you are sending ({"Name":"AA"}) it should be a class that has a Name property of type string.
// modify your action signature to look like this: [HttpPost] public ActionResult SaveProduct (Product product) { ... return Json(new { success = true }); }. Or get rid of this dataType: 'json' attribute from your AJAX request if you don't want to return JSON. In this case you could return simply status code 201 (Created with empty response body): return new HttpStatusCodeResult(201);.
[HttpPost]
public ActionResult SaveProduct(Product product)
{
using (var db = new KOEntities())
{
db.Products.Add(new Product { Name = product.Name, DateCreated = DateTime.Now });
db.SaveChanges();
}
return Json(new { success = true });
}
}
}
View:
#{
ViewBag.Title = "Knockout";
}
<h2>Knockout</h2>
<h3>Load JSON Data</h3>
<div id="loadJson-custom" class="left message-info">
<h4>Products</h4>
<div id="accordion" data-bind='template: { name: "product-template", foreach: product }'>
</div>
</div>
<h3>Post JSON Data</h3>
<div id="postJjson-custom" class="left message-info">
<h4>Add Product</h4>
<input id="productName" /><br />
<button id="addProduct">Add</button>
</div>
#section Scripts {
#Scripts.Render("~/bundles/knockout")
#Scripts.Render("~/bundles/livequery")
<script src="/Scripts/jquery.livequery.min.js"></script>
<style>
#accordion { width: 400px; }
</style>
<script id="product-template" type="text/html">
<h3><a data-bind="attr: {href:'#', title: Name, class: 'product'}"><span data-bind="text: Name"></span></a></h3>
<div>
<p>Here's some into about <span data-bind="text: Name" style="font-weight: bold;"></span> </p>
</div>
</script>
<script>
var isBound;
function loadJsonData() {
$.ajax({
url: "/knockout/GetProductList",
type: "GET",
contentType: "application/json",
dataType: "json",
data: {},
async: true,
success: function (data) {
var loadJsonViewModel = {
product: ko.observableArray(),
init: function () {
loadAccordion();
}
};
var a = $('loadJson-custom');
loadJsonViewModel.product = ko.mapping.fromJS(data);
if (isBound) { }
else
{
ko.applyBindings(loadJsonViewModel, $('loadJson-custom')[0]);
isBound = true;
}
loadJsonViewModel.init();
}
});
}
// push data back to the database
function pushJsonData(productName) {
var jData = '{"Name": "' + productName + '"}';
$.ajax({
url: "/knockout/SaveProduct",
type: "POST",
contentType: "application/json",
dataType: "json",
data: jData,
async: true,
success: function (data, textStatus, jqXHR) {
console.log(textStatus + " in pushJsonData: " + data + " " + jqXHR);
//ko.cleanNode($('loadJson-custom')[0]);
loadJsonData();
},
error: function (jqXHR, textStatus, errorThrown) {
alert(textStatus + " in pushJsonData: " + errorThrown + " " + jqXHR);
}
});
}
function loadAccordion() {
$("#accordion > div").livequery(function () {
if (typeof $("#accordion").data("ui-accordion") == "undefined")
{
$("#accordion").accordion({ event: "mouseover" });
}
else
{
$("#accordion").accordion("destroy").accordion({ event: "mouseover" });
}
});
}
$(function () {
isBound = false;
loadJsonData();
$("#addProduct").click(function () {
pushJsonData($("#productName").val());
});
});
</script>
}
Here is a complete solution for your question.
I have just implemented and checked.
Please have a look.
I have created a class for getting some records ie: Records.cs.
public static class Records
{
public static IList<Student> Stud(int size)
{
IList<Student> stud = new List<Student>();
for (int i = 0; i < size; i++)
{
Student stu = new Student()
{
Name = "Name " + i,
Age = 20 + i
};
stud.Add(stu);
}
return stud;
}
}
public class Student
{
public string Name { get; set; }
public int Age { get; set; }
}
Here is a controller for the respective view.
//
// GET: /HelpStack/
private static IList<Student> stud = Records.Stud(10);
public ActionResult HelpStactIndex()
{
return View();
}
[HttpGet]
public JsonResult GetRecord()
{
return Json(stud, JsonRequestBehavior.AllowGet);
}
[HttpPost]
public void PostData(Student model)
{
//do the required code here as All data is in "model"
}
Here is a view as HTML, I have taken two section one for list and other to Add records
<div id="loadJson-custom">
<h4>Student</h4>
<table width="100%">
<tr>
<td style="width: 50%">
<div id="accordion" data-bind='template: { name: "product-template", foreach: Student }'>
</div>
</td>
<td valign="top">
<div id="NewStudent">
<input type="text" data-bind="value: Name" /><br />
<input type="number" data-bind="value: Age" /><br />
<input type="submit" data-bind="click: Save" value="AddNew" />
</div>
</td>
</tr>
</table>
Here is your scripts for Knockoutjs.
<script id="product-template" type="text/html">
<h3><a data-bind="attr: { href: '#', title: Name, class: 'product' }"><span data-bind=" text: Name"></span></a>
<br />
Age: <span data-bind="text: Age"></span>
</h3>
<div>
<p>Here's some into about <span data-bind="text: Name" style="font-weight: bold;"></span></p>
</div>
</script>
<script type="text/javascript">
//Model for insert new record
var Model = {
Name: ko.observable(''),
Age: ko.observable(''),
};
var Student = ko.observableArray([]); // List of Students
function loadData() { //Get records
$.getJSON("/HelpStack/GetRecord", function (data) {
$.each(data, function (index, item) {
Student.push(item);
});
}, null);
}
function Save() { //Save records
$.post("/HelpStack/PostData", Model, function () { //Oncomplete i have just pushed the new record.
// Here you can also recall the LoadData() to reload all the records
//Student.push(Model);
Student.unshift(Model); // unshift , add new item at top
});
}
$(function () {
loadData();
ko.applyBindings(Model, $('#NewStudent')[0]);
});
</script>
You are declaring your model inside loadJsonData function success callback, & creating new object on every success callback, move the model outside that function, create an object & use it inside loadJsonData function, it will fix the issue.