mvc - binding JSON object - ajax

I am following a simple video tutorial for Knockout.js by Steve Sanderson:
http://channel9.msdn.com/Events/MIX/MIX11/FRM08
At the very end of it he performs an AJAX call to show how can you use knockout to process data on the server. I repeat all of what he is doing, but for some reason my JSON object doest bind to a POCO class correctly. This is an object I send from the view:
{"firstName":"Bartosz","lastName":"Malinowski","friends":[{"name":"Zofia"},{"name":"Zenon"}],"fullName":"Bartosz Malinowski"}
and then use this code to read it in the controller:
public JsonResult Save(Person person)
{
var message = string.Format("Saved {0} {1}", person.firstName, person.lastName);
return Json(new { message });
}
public class Person
{
public string firstName { get; set; }
public string lastName { get; set; }
public string fullName { get; set; }
public ICollection<Friend> friends { get; set; }
}
public class Friend
{
public string Name { get; set; }
}
}
My code on the client side looks like this:
'#{
ViewBag.Title = "Home Page";
}
<script src="../../Scripts/jquery.tmpl.js" type="text/javascript"></script>
<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"></span></p>
<h2>Friends (<span data-bind="text: friends().length"></span>)</h2>
<ul data-bind="template: { name: 'friendsTemplate', foreach: friends }"></ul>
<script id="friendsTemplate" type="text/html">
<li>
<input data-bind="value: name"/>
<button data-bind="click: remove">Remove</button></li>
</script>
<button data-bind="click: addFriend, enable: friends().length < 5">Add Friend</button>
<button data-bind="click: save">Save</button>
<script type="text/javascript">
function friend(name) {
return {
name: ko.observable(name),
remove: function () {
viewModel.friends.remove(this);
}
};
}
var viewModel = {
firstName: ko.observable("Bartosz"),
lastName: ko.observable("Malinowski"),
friends: ko.observableArray([new friend("Zofia"), new friend("Zenon")]),
addFriend: function () {
this.friends.push(new friend("Jan"));
},
save: function () {
$.ajax({
url: "#Url.Action("Save")",
type: "post",
data: ko.toJSON(this),
contenttype: "application/json",
success: function (result) { alert(result.message) }
});
}
};
viewModel.fullName = ko.dependentObservable(function () {
return this.firstName() + " " + this.lastName();
}, viewModel);
ko.applyBindings(viewModel);
</script>
When I run it in debug mode and check person in the Save method parameter I've got null value for each Person property. So it just doesn't bind to me??

I do exactly the same here is my code
$.ajax({
url: url,
type: "POST",
dataType: "json",
data: ko.toJSON(viewModel),
contentType: 'application/json; charset=utf-8',
success: function (returnedData)
{
window.location.replace(urlRedirect);
}
});
There is a few differences : dataType and the charset, I'd say that it's the dataType.
I also have the [HttpPost] on my action.

Related

Model validation in Asp.Net Core before making an Ajax call from java script

Below is the sample code, i am calling this code on button click event. My question is, can i validate my viewmodel object before making ajax call? i can see model errors in java script, not sure how to check.
My viewmodel class properties has Data Annotation Validator Attributes. I don't want make ajax call if the viewmodel is not valid, want to check (ModelState.IsValid) in java script code, before making ajax call.
Any help, would be greatly appreciated.
$(function () {
$("#btnGet").click(function () {
var viewModelobject = {};
viewModelobject.Name = $("#txtName").val();
$.ajax({
type: "POST",
url: "/Home/AjaxMethod",
data: viewModelobject,
contentType: "application/json",
dataType: "json",
success: function (response) {
alert("Hello")
}
});
});
}
ModelState.IsValid is server side code.Browser has no idea about what it is,so you could not validate ModelState in client side. You can use Jquery Validation at client side.
Here is a working demo:
1.Model:
public class UserModel
{
[Required(ErrorMessage = "The Name field is required.")]
[Display(Name = "Name")]
public string Name { get; set; }
}
2.View(Index.cshtml):
#model UserModel
<form id="frmContact">
<div asp-validation-summary="ModelOnly" class="text-danger"></div>
<div class="form-group">
<label asp-for="Name" class="control-label"></label>
<input asp-for="Name" id="txtName" class="form-control" />
<span asp-validation-for="Name" class="text-danger"></span>
</div>
<div class="form-group">
<button type="submit" class="btn btn-secondary" id="btnGet">Click</button>
</div>
</form>
#section Scripts
{
#*you could also add this partial view*#
#*#{await Html.RenderPartialAsync("_ValidationScriptsPartial");}*#
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery-validate/1.15.1/jquery.validate.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery-validation-unobtrusive/3.2.6/jquery.validate.unobtrusive.min.js"></script>
<script>
$(function () {
$('#btnGet').click(function () {
if ($("#frmContact").valid()) {
$('#frmContact').submit();
}
else {
return false;
}
});
$("#frmContact").on("submit", function (event) {
event.preventDefault();
var viewModelobject = {};
viewModelobject.Name = $("#txtName").val();
$.ajax({
type: "POST",
url: "/Home/AjaxMethod",
data: JSON.stringify(viewModelobject),
contentType: "application/json",
dataType: "json",
success: function (response) {
alert("Hello")
}
});
});
})
</script>
}
3.Controller:
public class HomeController : Controller
{
public IActionResult Index()
{
return View();
}
[HttpPost]
public IActionResult AjaxMethod([FromBody]UserModel user)
{
//do your stuff...
return Json(user);
}
}
Result:
Please use jQuery form validation as shown below inside the button click callback:
var form = $('form[name="' + formName + '"]');
form.validate();
if (form.valid()) {
//Do something if the form is valid
}
else {
//Show validation error messages if the form is in-valid
}

Aspnet Core - Error 400 When i send Httpost with js

I need to get a list permissao when I select a group, I made the methods but when I select the group, it returns me an error.
PermissaoGrupo/ObterPermissoesAdd:1 Failed to load resource: the
server responded with a status of 400 ()
View
#model RKMES.Models.ViewModel.PermissaoGrupoViewModel
<script type="text/javascript" src="assets/js/plugins/forms/inputs/duallistbox.min.js"></script>
<script type="text/javascript" src="assets/js/pages/form_dual_listboxes.js"></script>
<h2>Index</h2>
<div class="form-group">
#*<label asp-for="Grupos" class="control-label">Grupo</label>*#
#*<select class="custom-select custom-select-sm" asp-items="#(new SelectList(Model.Grupos,"Id","Nome"))"></select>*#
Grupos
#Html.DropDownList("Grupos", new SelectList(Model.Grupos,"Id", "Nome"))
</div>
<!-- Filtered results -->
<div class="panel panel-flat">
<div class="panel-heading">
<h5 class="panel-title">Filtered results</h5>
</div>
<div class="panel-body">
#*<select multiple="multiple" class="form-control listbox-no-selection" asp-items="#(new SelectList(Model.Permissoes,"Id","Nome"))"></select>*#
#Html.DropDownList("Permissoes", new SelectList(Enumerable.Empty<SelectListItem>(), "Id", "Nome"))
</div>
</div>
<!-- /filtered results -->
<script type="text/javascript">
$(document).ready(function () {
$('#Grupos').change(function () {
var idGrupo = $('#Grupos').val();
if (idGrupo > 0) {
$.post('#Url.Action("ObterPermissoesAdd", "PermissaoGrupo")', { 'idGrupo': idGrupo }, function (data) {
if (data.length > 0) {
for (var i = 0; i < data.length; i++) {
$('#Permissoes').append('<option value="' +data[i].Id+ '">' + data[i].Nome+ '</option>');
}
}
});
}
});
});
</script>
PermissaoGrupoController
[HttpPost]
[ValidateAntiForgeryToken]
public IActionResult ObterPermissoesAdd(int idGrupo)
{
return Json(_grupoContext.GetPermissoesAdd(idGrupo));
}
GrupoService
public async Task<List<Permissao>> GetPermissoesAdd(int id)
{
return await _context.Grupo_Permissao_Permissao
.Where(x => x.Grupo_PermissaoId == id)
.Select(x => x.Permissao)
.ToListAsync();
}
Model
namespace RKMES.Models
{ // essa é uma tabela intermediaria das entidades Grupo_Permissao e Permissao
public class Grupo_Permissao_Permissao
{
public int Id { get; set; }
public int Grupo_PermissaoId { get; set; }
public int PermissaoId { get; set; }
public virtual Grupo_Permissao Grupo_Permissao { get; set; }
public virtual Permissao Permissao { get; set; }
}
}
What am I doing wrong?
For your issue, it is caused by ValidateAntiForgeryToken. which will check whether the request contains RequestVerificationToken header.
For a quick test, you could remove [ValidateAntiForgeryToken] from Controller.
For a recommended way, you need to attach the anti forgery token like
<script type="text/javascript">
$(document).ready(function(){
var Group = {
GroupId: 1,
GroupName: "My Group Name"
};
AjaxPost("/Groups/AddGroup", Group).done(function () {
GetGroups();
});
});
function gettoken() {
var token = '#Html.AntiForgeryToken()';
token = $(token).val();
return token;
}
function AjaxPost(url, data) {
return $.ajax({
type: "post",
contentType: "application/json;charset=utf-8",
dataType: "json",
responseType: "json",
url: url,
headers: {
"RequestVerificationToken": gettoken()
},
data: JSON.stringify(data)
});
}
</script>

Pass multiple Id's against multiple values in database

I'm working on a task that uses autocomplete textbox items containing names, stores in textbox or in listbox with their associated Id's(hidden) and inserted into the required table (only their related id's). I'm working on mvc 5 application. So far I've achieved to add value in listbox with names but not Id's. And trying to add the listbox values get stored in database. Below is my code.
Note:- I'm using partial view to display listbox when the button clicks. The current scenario is that it the listbox overwrites the first value when inserting second value.
StudentBatch.cs
public List<string> selectedids { get; set; }
public List<string> SelectedNames { get; set; }
Create.cshtml
<div class="form-group">
<div class="col-md-12">
#Html.EditorFor(model => model.StudentName, new { id = "StudentName" })
<input type="button" value="Add Text" id="addtypevalue" />
<div id="typevaluelist"></div>
</div>
</div>
<div id="new" style="display:none;">
<div class="typevalue">
<input type="text" name="typevalue" />
<button type="button" class="delete">Delete</button>
</div>
</div>
<div class="form-group">
<div class="col-md-offset-2 col-md-10">
<input type="submit" value="Add Students" class="btn btn-default" />
</div>
</div>
<script type="text/javascript">
$(document).ready(function () {
$("#StudentName").autocomplete({
//autocomplete: {
// delay: 0,
// minLength: 1,
source: function (request, response)
{
$.ajax({
url: "/Student/CreateStudent",
type: "POST",
dataType: "json",
data: { Prefix: request.term },
success: function(data) {
try {
response($.map(data,
function (item)
{
return { label: item.FirstName, value: item.FirstName };
}));
} catch (err) {
}
}
});
},
messages:
{
noResults: "jhh", results: "jhjh"
}
});
});
</script>
<script>
$('#addtypevalue').click(function () {
$(document).ready(function () {
var selValue = $('#StudentName').val();
$.ajax({
type: "GET",
url: '#Url.Action("GetListBox", "Student")',
dataType: "html",
data: { CourseId: selValue },
success: function (data) {
$("#partialDiv").html(data);
},
failure: function (data) {
alert('oops something went wrong');
}
});
});
});
</script>
GetListBox.cshtml
#model WebApplication1.Models.StudentBatch
#if (ViewBag.Value != null)
{
#Html.ListBoxFor(m => m.SelectedNames, new SelectList(Model.SelectedNames))
}
StudentController.cs
public PartialViewResult GetListBox(string CourseID)
{
Context.Student studCont = new Context.Student();
Models.StudentBatch student = new Models.StudentBatch();
student.SelectedNames = new List<string>();
student.SelectedNames.Add(CourseID);
ViewBag.Value = student;
return PartialView(student);
}

Ajax Post: ASP.NET MVC action is receiving empty object

I have this form:
#model CupCakeUI.Models.CupCakeEditViewModel
#using (Html.BeginForm(null, null, FormMethod.Post, new { id = "createFrm" }))
{
<div class="form-group">
<div class="editor-label">
#Html.LabelFor(model => model.Name)
</div>
<div class="editor-field">
<input type="text" id="Name" name="Name" value="#Model.Name" />
</div>
<div class="editor-label">
#Html.LabelFor(model => model)
</div>
<div class="editor-field">
<input type="text" id="Price" name="Price" value="#Model.Price" />
</div>
<div class="col-md-offset-2 col-md-10">
<input type="button" id="btnCreate" value="Create" class="btn btn-default" />
</div>
</div>
}
I am trying to use ajax post to send data to the Action Method, however its always receiving empty object. I have done that several times in the past, and now i tried different ways which not working, The code:
$(document).ready(function () {
$("#btnCreate").click(function () {
var name = $("#Name").val();
var price = $("#Price").val();
var cupCakeEditModel = { "CupCakeId": 0, "Name": name, "Price": price };
var json = JSON.stringify(cupCakeEditModel);
$.ajax({
type: 'POST',
url: "/CupCake/Create",
data: JSON.stringify(cupCakeEditModel),
contentType: 'application/json',
success: function () {
alert("succes");
},
error: function () {
alert("error");
}
});
})
})
Its showing this in the console when logging:
This is the Action Method and Class used:
[HttpPost]
public JsonResult Create (CupCakeUI.Models.CupCakeEditViewModel cupCakeEditModel)
{
var cupCake =
CupCakeData.Save(cupCakeEditModel);
return Json("cupCake",
JsonRequestBehavior.AllowGet);
}
This the class:
public class CupCakeEditViewModel
{
public int CupCakeId;
[Display(Name = "CupCake Name")]
public string Name;
public string Price;
}
I have also used this, but not working:
$("#btnCreate").click(function () {
var cupCakeEditModel =
$("#createFrm").serialize();
$.ajax({
url: "/CupCake/Create",
type: "POST",
data: cupCakeEditModel,
success: function (response) {
alert("Success");
},
error: function (response) {
}
});
})
And several answers i found on the forum, but it seems something weird!
You model contains only fields, and the DefaultModelBinder does not bind fields, only properties. Change the model to
public class CupCakeEditViewModel
{
public int CupCakeId { get; set; }
[Display(Name = "CupCake Name")]
public string Name { get; set; }
public string Price { get; set; }
}

Kendo-Knockout reference with MVC using Database First Approach [closed]

Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 8 years ago.
Improve this question
I am looking for Kendo-Knockout reference with MVC using Database First Approach.
Please look at my code below,
<script type="text/javascript">
$(document).ready(function () {
var ViewModel = function () {
var self = this;
self.Id = ko.observable();
self.Name = ko.observable();
self.Category = ko.observable();
self.Price = ko.observable();
var Product = {
Id: self.Id,
Name: self.Name,
Category: self.Category,
Price: self.Price
};
self.Product = ko.observable();
self.Products = ko.observableArray();
$.getJSON("/Product/GetProoducts", function (data) {
self.Products(data);
$.each(data, function (index) {
})
});
self.Create = function () {
if (Product.Name() != "" && Product.Price() != "" && Product.Category() != "") {
$.ajax({
url: '#Url.Action("AddProduct", "Product")',
cache: false,
type: 'POST',
contentType: 'application/json; charset=utf-8',
data: ko.toJSON(Product),
success: function (data) {
self.Products.push(data);
self.Name("");
self.Price("");
self.Category("");
}
}).fail(function (xhr, textStatus, err) {
alert(err);
});
}
}
}
ko.applyBindings(new ViewModel());
});
I am getting an issue with the above code. I need to do CRUD operation using kendo - knockout js.
Please find below code ,
Repository
interface IProductRepository : IDisposable
{
IEnumerable<Product> GetAll();
Product Get(int id);
Product Add(Product item);
bool Update(Product item);
bool Delete(int id);
void Save();
}
public class ProductRepository : IProductRepository, IDisposable
{
RepositoryEntities context = null;
public ProductRepository()
{
context = new RepositoryEntities();
}
public ProductRepository(RepositoryEntities context)
{
this.context = context;
}
public IEnumerable<Product> GetAll()
{
return context.Products.ToList();
}
public Product Get(int id)
{
return context.Products.Find(id);
}
public Product Add(Product item)
{
Product newProduct = context.Products.Add(item);
int id = context.SaveChanges();
return newProduct;
}
public bool Update(Product item)
{
context.Entry(item).State = EntityState.Modified;
context.SaveChanges();
return true;
}
public bool Delete(int id)
{
Product objProduct = context.Products.Find(id);
context.Products.Remove(objProduct);
context.SaveChanges();
return true;
}
public void Save()
{
context.SaveChanges();
}
private bool disposed = false;
protected virtual void Dispose(bool disposing)
{
if (!this.disposed)
{
if (disposing)
{
context.Dispose();
}
}
this.disposed = true;
}
public void Dispose()
{
Dispose(true);
GC.SuppressFinalize(this);
}
}
Controller
public class ProductController : Controller
{
// private IProductRepository productRepository;
private IProductRepository repository = new ProductRepository();
//public ProductController(IProductRepository repository)
//{
// this.productRepository = repository;
//}
//
// GET: /Product/
public ActionResult Index()
{
return View();
}
public JsonResult GetProoducts()
{
return Json(repository.GetAll(), JsonRequestBehavior.AllowGet);
}
public JsonResult AddProduct(Product item)
{
item = repository.Add(item);
return Json(item, JsonRequestBehavior.AllowGet);
}
public JsonResult EditProduct(int id, Product product)
{
product.Id = id;
if (repository.Update(product))
{
return Json(repository.GetAll(), JsonRequestBehavior.AllowGet);
}
return Json(null);
}
public JsonResult DeleteProduct(int id)
{
if (repository.Delete(id))
{
return Json(new { Status = true }, JsonRequestBehavior.AllowGet);
}
return Json(new { Status = false }, JsonRequestBehavior.AllowGet);
}
}
View
#{
ViewBag.Title = "Index";
}
<script src="~/jquery.min.js"></script>
<script src="~/kendo.all.min.js"></script>
<script src="~/knockout-3.1.0.js"></script>
<script src="~/knockout-kendo.min.js"></script>
<link href="~/kendo.silver.min.css" rel="stylesheet" />
<div id="body">
<h2>Kendo Knockout CRUD Operations</h2>
<div data-bind="kendoGrid: { data : Products, rowTemplate: 'rowTmpl', scrollable: true, sortable: true, useKOTemplates: true}">
</div>
<script id="rowTmpl" type="text/html">
<tr>
<td data-bind="text: Id"></td>
<td data-bind="text: Name"></td>
<td data-bind="text: Price"></td>
<td data-bind="text: Category"></td>
<td> <button data-bind="click: $root.Edit">Edit</button></td>
<td> <button data-bind="click: $root.Delete">Delete</button></td>
</tr>
</script>
<br/>
<div data-bind="if: Product">
<div>
<h2>Update Product</h2>
</div>
<div>
<label for="productId" data-bind="visible: false">ID</label>
<label data-bind="text: Product().Id, visible: false"></label>
</div>
<div>
<label for="name">Name</label>
<input data-bind="value: Product().Name" type="text" title="Name" />
</div>
<div>
<label for="category">Category</label>
<input data-bind="value: Product().Category" type="text" title="Category" />
</div>
<div>
<label for="price">Price</label>
<input data-bind="value: Product().Price" type="text" title="Price" />
</div>
<br />
<div>
<button data-bind="click: $root.Update">Update</button>
<button data-bind="click: $root.Cancel">Cancel</button>
</div>
</div>
<br />
<div data-bind="ifnot: Product()">
<div>
<h2>Add New Product</h2>
</div>
<div>
<label for="name">Name</label>
<input data-bind="value: $root.Name" type="text" title="Name" />
</div>
<div>
<label for="price">Price</label>
<input data-bind="value: $root.Price" type="text" title="Price" />
</div>
<div>
<label for="category">Category</label>
<input data-bind="value: $root.Category" type="text" title="Category" />
</div>
<div>
<button data-bind="click: $root.Create">Save</button>
<button data-bind="click: $root.Reset">Reset</button>
</div>
</div>
</div>
<script type="text/javascript">
$(document).ready(function () {
var ViewModel = function () {
var self = this;
self.Id = ko.observable();
self.Name = ko.observable();
self.Category = ko.observable();
self.Price = ko.observable();
var Product = {
Id: self.Id,
Name: self.Name,
Category: self.Category,
Price: self.Price
};
self.Product = ko.observable();
self.Products = ko.observableArray();
$.getJSON("/Product/GetProoducts", function (data) {
self.Products(data);
$.each(data, function (index) {
})
});
self.Create = function () {
if (Product.Name() != "" && Product.Price() != "" && Product.Category() != "") {
$.ajax({
url: '#Url.Action("AddProduct", "Product")',
cache: false,
type: 'POST',
contentType: 'application/json; charset=utf-8',
data: ko.toJSON(Product),
success: function (data) {
self.Products.push(data);
self.Name("");
self.Price("");
self.Category("");
}
}).fail(function (xhr, textStatus, err) {
alert(err);
});
}
}
self.Reset = function () {
self.Name("");
self.Price("");
self.Category("");
}
// Edit product details
self.Edit = function (Product) {
self.Product(Product);
}
// Cancel product Details
self.Cancel = function () {
self.Product(null);
}
//Update Product Details
self.Update = function () {
var Product = self.Product();
$.ajax({
url: '#Url.Action("EditProduct", "Product")',
cache: false,
type: 'POST',
contentType: 'application/json; charset=utf-8',
data: ko.toJSON(Product),
success: function (data) {
self.Products.removeAll();
self.Products(data); //Put the response in ObservableArray
self.Product(null);
alert("Record Updated Successfully");
}
}).fail(function (xhr, textStatus, err) { alert(err); });
}
//Delete Product Details
self.Delete = function (Product) {
if (confirm('Are you sure to Delete "' + Product.Name + '" product ??'))
{
var id = Product.Id;
$.ajax({
url: '/Product/DeleteProduct/'+ id,
cache: false,
type: 'POST',
contentType: 'application/json; charset=utf-8',
data: ko.toJSON(id),
success: function (data) {
self.Products.remove(Product);
}
}).fail(
function (xhr, textStatus, err) {
self.status(err);
});
}
}
}
ko.applyBindings(new ViewModel());
});
</script>
Please find below links too,
http://www.dotnet-tricks.com/Tutorial/knockout/0bOU010413-Knockout-CRUD-Operations-using-MVC4.html
http://pinaki-mukherjee.blogspot.in/2013/01/kendo-knockout-grid-bind.html
http://www.c-sharpcorner.com/uploadfile/yusufkaratoprak/asp-net-mvc-with-knockout-js/
http://www.codeproject.com/Articles/640294/Learning-MVC-Part-Generic-Repository-Pattern-in

Resources