Why sending JSON data via POST (ajax) returns null parameter? - ajax

Good afternoon everybody :)
I am working on asp.net mvc application.
I am using JQuery DataTable in order to show my data.
Actually, my ajax Post request calls a controller method which has to receive some parameters.
The problem is that they are null. I also have the Post 500 error :(
Here is my class:
public class ClientSelectionFiltersViewModel
{
public bool StrictFilteringContractTypes { get; set; }
public string ContractTypes { get; set; }
public string PaymentChoices { get; set; }
public string PopulationTypes { get; set; }
}
Here is a part of cshtml view:
#model ClientSelectionViewModel
#{
ViewBag.Title = "Sélection des clients";
}
<link href="~/lib/datatables/css/dataTables.bootstrap4.min.css" rel="stylesheet" />
<h3><i class="fas fa-clipboard-list mr-3"></i> Sélection des clients</h3>
<div asp-validation-summary="All" class="text-danger mt-2"></div>
<div id="filters">
<form method="post" asp-action="facturationWithFilters">
<!--some code here-->...
</form>
<button id="btn-filter-clients" class="btn atmb-btn-blue"><i class="fas fa-filter fa-fw mr-2"></i>Filtrer les clients</button>
</div>
<div id="client-selection" class="mt-2">
<div class="mb-1">
<a id="btn-send-selection" class="btn float-right atmb-btn-red">
<i class="fas fa-feather-alt fa-fw mr-2"></i>Lancer la facturation pour les utilisateurs sélectionnés
</a>
</div>
<table class="table table-striped table-hover table-sm table-bordered"
id="tableServerSide"
style="width:100%;">
<thead class="thead-dark text-white">
<tr>
<th>Cocher</th>
<th>#</th>
<th>Numéro de client</th>
<th>Types de contrats</th>
<th>Moyen de paiement</th>
<th>Population</th>
</tr>
</thead>
<tbody>
</tbody>
</table>
</div>
#section Scripts {
<!--scripts DataTable-->
<script src="~/js/modal.js"></script>
<script src="~/lib/datatables/js/jquery.dataTables.min.js"></script>
<script src="~/lib/datatables/js/dataTables.bootstrap4.min.js"></script>
<!--script pour la gestion de DataTable-->
<script type="text/javascript">
$('#btn-filter-clients').click(function () {
console.log($("#contractFilter").val()); //ok I get my values
console.log($("#paymentFilter").val()); //ok I get my values
console.log($("#populationFilter").val()); //ok I get my values
console.log("début Data Table");
$("#tableServerSide").DataTable({
"processing": true,
"serverSide": true,
"filter": true,
"ajax": {
"url": "/clientselection/ajaxpostcall",
"type": "POST",
"datatype": "json",
"data": JSON.stringify({
filters: {
"ContractTypes": $("#contractFilter").val(),
"PaymentChoices": $("#paymentFilter").val(),
"PopulationTypes": $("#populationFilter").val(),
"StrictFilteringContractTypes": $("#StrictFilteringContractTypes").is(":checked")
}
}),
"contentType": "application/json",
"success": function (response) {
if (response != null) {
alert("Name : " + response.Name + ", Designation : " + response.Designation + ", Location :" + response.Location);
} else {
alert("Something went wrong");
}
},
"failure": function (response) {
alert(response.responseText);
},
"error": function (response) {
alert(response.responseText);
}
},
"columns": [ // on définit les colonnes du tableau
{
//Cases cocher
"data": null,
"className": "col-checkbox",
"render": function (data, type, row) {
var checkId = 'check' + row.id;
var isChecked = selectedIds.includes(checkId) ? ' checked="checked"' : '';
var checkbox = '<input id="' + checkId + '" type="checkbox" '
+ isChecked
+ ' class="server-checkbox" /> ';
/*
<td class="col-checkbox sorting_1">
<input id="check0" type="checkbox" class="server-checkbox">
</td>
*/
return checkbox;
}
},
{
//Numéro de client
"data": "id",
"className": "col-id"
},
{
//Types de contrats
"data": "contractstypes",
"className": "col-contractstypes",
"render": function (data, type, row) {
var chaine = string.Join(", ", row.value);
return chaine;
}
},
{
//Moyen de paiement PaymentChoice
"data": "paymentchoice",
"className": "col-paymentchoice"
},
{
//Population PopulationType
"data": "populationtype",
"className": "col-populationtype"
}
]
});
});
</script>
}
Here is my controller method:
[HttpPost]
public async Task<JsonResult> AjaxPostCall(ClientSelectionFiltersViewModel filters)
{
//some code here....
return Json(result);
}
I red at least 6 solutions which didn't work for me such as :
in ajax:
"data": JSON.stringify({
filters: {
ContractTypes: $("#contractFilter").val(),
PaymentChoices: $("#paymentFilter").val(),
PopulationTypes: $("#populationFilter").val(),
StrictFilteringContractTypes: $("#StrictFilteringContractTypes").is(":checked")
}
}),
and then in the controller :
[HttpPost]
public async Task<JsonResult> AjaxPostCall([FromBody] ClientSelectionFiltersViewModel filters)
{
//some code here....
return Json(result);
}
don't specify the "contentType": "application/json",
use different syntax of my json data with or without " "
...
Can you please tell me how to fix it?
Thanks I a lot.

You won't likely need [FromBody] on your action; try changing your JSON.stringify to:
"data": JSON.stringify({
"ContractTypes": $("#contractFilter").val(),
"PaymentChoices": $("#paymentFilter").val(),
"PopulationTypes": $("#populationFilter").val(),
"StrictFilteringContractTypes": $("#StrictFilteringContractTypes").is(":checked")
}),

This solution worked for me :
[HttpPost]
public async Task<JsonResult> AjaxPostCall(ClientSelectionFiltersViewModel filters, DataTableRequestParameters parameters)
{
//somecode...
}
And in JQuery :
var filters = {
ContractTypes: $("#contractFilter").val().join(', '),
PaymentChoices: $("#paymentFilter").val().join(', '),
PopulationTypes: $("#populationFilter").val().join(', '),
StrictFilteringContractTypes: $("#StrictFilteringContractTypes").is(":checked")
}
$("#tableServerSide").DataTable({
"processing": true,
"serverSide": true,
"filter": true,
"ajax": {
//"url": "/clientselection/ajaxpostcall", //doesn't work!!!
"url": "#Url.Action("AjaxPostCall", "ClientSelection")", //ok because of tag helper
"type": "POST",
"data": filters,
......
Thanks for your help!!

Remove "contentType"
Set "data" : jsonObject; without JSON.Stringy();
Remove [FromBody] from controller action method

Related

Anyone can tell me whats wrong in here when im putting a array of number like :1,2 its starting to freeze the screen i hope someone can help me thanks

Hello guys im trying to learn vue and im trying to use datatable from https://datatables.net/ and having a problem with my action button that im not able to get the id when the #viewModal is been triggered i hope someone can help me to get the id of each buttons thanks and here is my code TIA:
EmployeeDataTable Component :
<template>
<div class="card">
<div class="card-header">
<div class="card-title">Employee List</div>
</div>
<div class="card-body">
<div class="table-responsive">
<table
id="employee-table"
class="table-sm table-bordered table-hover text-center display"
width="100%"
>
<thead>
<tr>
<th class="pt-3 pb-3">#</th>
<th>Name</th>
<th>Address</th>
<th>Contact #</th>
<th>Department</th>
<th>Status</th>
<th>Actions</th>
</tr>
</thead>
<tbody></tbody>
</table>
</div>
</div>
</div>
</template>
<script>
//For Datatable to work
import "datatables.net";
import EmployeeEdit from "./EmployeeEdit.vue";
export default {
name: "EmployeeList",
data() {
return {
employees: [],
};
},
mounted() {
this.getEmployeeLists();
},
components: {
"employee-edit": EmployeeEdit,
},
methods: {
getEmployeeLists() {
// INITIALIZE DATATABLE
$("#employee-table")
.DataTable({
//LOADING
// processing: true,
//AJAX
serverSide: true,
//DIRECTION
order: [[1, "desc"]],
//AJAX
ajax: {
url: "/api/getEmployeeLists",
dataList: "json",
type: "POST",
data: { _token: "{{csrf_token()}}" },
},
//TABLE COLUMNS SHOULD BE THE SAME IN CONTROLLER
columns: [
{ data: "#" },
{ data: "name" },
{ data: "address" },
{ data: "contact" },
{ data: "department" },
{ data: "status" },
{
data: "actions",
//allowing modification
createdCell(cell, cellData, rowData) {
let EmployeeListDataTableActions = Vue.extend(
require("./EmployeeListDataTableAction.vue").default
);
let instance = new EmployeeListDataTableActions().$mount();
$(cell).empty().append(instance.$el);
},
},
],
//View Count in Table
lengthMenu: [
[10, 25, 50, -1],
[10, 25, 50, "All"],
],
})
.columns();
},
beforeDestroy: function () {
$(this.$el).DataTable().destroy();
},
},
};
</script>
EmployeeDataTableAction Component :
<template>
<button class="btn btn-primary btn-sm" #click="viewModal" title="View Employee Details">
<i class="fa fa-eye"></i>
</button>
</template>
<script>
export default{
name: 'EmployeeListDataTableAction',
data: function() {
return {
}
},
mounted() {
},
methods: {
viewModal() {
var id = $(this.$el).closest('tr').find('input').val();
return false;
axios
.post(`/api/getEmployeeDetails/${id}`, {
id: id,
})
.then((response) => {
$("#edit-employee-modal").modal("show");
$(".myModalLabel").text(
response.data.name +
" - " +
response.data.department_name
);
state.commit("getEmployeeDetailsArray", response.data);
state.commit("getTransactionId", response.data.id);
})
.catch((response) => {
this.$toast.top("Something went wrong!");
});
},
},
}
</script>
Employee Controller for the DataTable :
public function employeeList(Request $request){
$all = Employee::getEmployeeTotal();
//total count of data
$total_data = $all;
//total filter
$total_filtered = $total_data;
//set_time_limit(seconds)
$limit = $request->input('length');
//start
$start = $request->input('start');
//order
// $order = $columns[$request->input('order.0.column')];
//direction
$dir = $request->input('order.0.dir');
$search_value = $request->input('search.value');
if (!empty($search_value)) {
$posts = Employee::getEmployeeNameSearch($search_value,$start, $limit, $dir);
$total_data = count($posts);
$total_filtered = $total_data;
}else{
if(empty($request->input('search.value')))
{
//if no search
$posts = Employee::getEmployeeList($start, $limit, $dir);
}
}
$data = array();
if(!empty($posts))
{
$counter = $start + 1;
foreach ($posts as $post)
{
$department = GlobalModel::getSingleDataTable('departments',$post->department_id);
$status = StatusController::checkStatus($post->status);
$nested_data['#'] = '<span style="font-size: 12px ; text-align: center;">'.$counter++.'</span>';
$nested_data['name'] = '<p style="text-align: center;">'.$post->name.'</p>';
$nested_data['address'] = '<p style="text-align: center;">'.$post->address.'</p>';
$nested_data['contact'] = '<p style="text-align: center;">'.$post->contact.'</p>';
$nested_data['department'] = '<p style="text-align: center;">'.$department->name.'</p>';
$nested_data['status'] = '<p style="text-align: center;">'.$status.'</p>';
$nested_data['actions'] = '';
$data[] = $nested_data;
}
}
$json_data=array(
"draw" => intval($request->input('draw')),
"recordsTotal" => intval($total_data),
"recordsFiltered" => intval($total_filtered),
"data" => $data
);
return response()->json($json_data);
}
In the second line of your viewModal() function, you are placing a return false; statement. "The return statement ends function execution and specifies a value to be returned to the function caller." From Mozilla docs. That's why the API call is never executing.

C# jQuery Ajax Datatables ASP.NET Core 5 MVC

I am attempting to implement ASP.NET Core SignalR. I am looking for assistance. The project is located at: https://github.com/Talsiter/AspNetCore-SignalR-SqlTableDependency
The issue that I am running into is when a datatable is being populated from jQuery AJAX, no data is being populated into the view.
Items model (Item.cs)
using System.ComponentModel;
using System.ComponentModel.DataAnnotations;
namespace InAndOut.Models
{
public class Item
{
[Key]
public int Id { get; set; }
public string Borrower { get; set; }
public string Lender { get; set; }
[DisplayName("Item name")]
public string ItemName { get; set; }
}
}
Items view (Index.cshtml)
#model IEnumerable<InAndOut.Models.Item>
<div class="container p-3">
<div class="row">
<div class="col-12">
<div class="card">
<div class="card-header">
<div class="card-body">
<table id="myTable" class="table table-bordered table-striped">
<thead>
<tr>
<th>Id</th>
<th>Item Name</th>
<th>Borrower</th>
<th>Lender</th>
<th>Action</th>
</tr>
</thead>
</table>
</div>
</div>
</div>
</div>
</div>
#section Scripts {
#* These Scrips are Required *#
<script src="~/js/signalr/dist/browser/signalr.js"></script>
#*This one gives me an error of "ItemsHub undefined"*#
#*<script src="~/js/items01.js"></script>*#
#* This gives me an error "DataTable is not a function"
This probably requires the *#
<link href="//cdn.datatables.net/1.10.25/css/jquery.dataTables.min.css" rel="stylesheet" />
<script type="text/javascript" src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
<script type="text/javascript" src="https://cdnjs.cloudflare.com/ajax/libs/datatables/1.10.21/js/jquery.dataTables.min.js"></script>
<script src="~/js/items03.js"></script>
}
Items JS file (items03.js):
// This is from:
//https://stackoverflow.com/questions/51764211/jquery-datatable-loading-using-ajax-asp-net-mvc
// Does Not Display any data
function getAllMessages() {
$('#myTable').DataTable({
processing: true,
serverSide: false,
ordering: true,
paging: true,
searching: true,
columns: [
{ title: "Id" },
{ title: "ItemName" },
{ title: "Borrower" },
{ title: "Lender" },
{ title: "View Data" }
],
columns: [
{ data: "Id" },
{ data: "ItemName" },
{ data: "Borrower" },
{ data: "Lender" },
{
data: null,
defaultContent: "<button class='tblview'>View Id</button><button class='tblDelete'>Delete</button>"
}
],
ajax: {
"url": "/Item/GetItems",
"type": "GET",
"dataSrc": ''
},
"columnDefs": [
{
"targets": 0,
"visible": false
}
]
});
}
Item controller (ItemController.cs):
// This was updated from:
// https://stackoverflow.com/questions/51705732/jquery-datatable-ajax-no-data-available-mvc
public IActionResult GetItems()
{
var items = new List<Item>
{
new Item { Id = 1, ItemName = "Computer", Borrower = "Justin", Lender = "Don"},
new Item { Id = 2, ItemName = "Mouse", Borrower = "Mark", Lender = "Susan"},
new Item { Id = 3, ItemName = "Monitor", Borrower = "Mark", Lender = "Joe"},
new Item { Id = 4, ItemName = "Keyboard", Borrower = "Candace", Lender = "Angela"},
new Item { Id = 5, ItemName = "Printer", Borrower = "Mike", Lender = "Watson"},
};
// JsonRequestBehavior requires Microsoft.AspNet.MVC
// I do not want to reference it. I want to use Microsoft.AspNetCore.Mvc
//return Json(items, JsonRequestBehavior.AllowGet);
// I referenced this to mitigate the above issue
// https://stackoverflow.com/questions/38578463/asp-net-core-the-name-jsonrequestbehavior-does-not-exist-in-the-current-cont
//return Json(items);
// Error: Cannot read property 'style' of undefined
// This was another option
//return Json(items, new Newtonsoft.Json.JsonSerializerSettings());
// Error: Cannot read property 'style' of undefined
// This seems to be returning the correct data format
// Now the data just is not being displayed in the view
// My error seems to be in the JavaScript
return Json(new { data = items });
}
After many attempts, this is about the closest that I am able to get. While debugging the site, I do not receive any errors, but the mock data does not appear in the items view.
I am suspecting that my issue is in the Items JS file in the getAllMessages() method. I am just not sure how to fix it.
The naming convention for response in asp.net core is camel case instead of pascal case. Also you need remove "dataSrc": ''.
Change like below:
columns: [
{ data: "id" },
{ data: "itemName" },
{ data: "borrower" },
{ data: "lender" },
{
data: null,
defaultContent: "<button class='tblview'>View Id</button><button class='tblDelete'>Delete</button>"
}
],
ajax: {
"url": "/Item/GetItems",
"type": "GET",
//"dataSrc": ''
},

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);
}

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

update model with ajax in razor

i write this code with ajax to delete some info after that i update my updateAjax div with ajax for refreshing content and this view have masterpage.in picture u see what happen.
this is my code
#using Common.UsersManagement.Entities;
#model IEnumerable<VwUser>
#{
Layout = "~/Views/Shared/Master.cshtml";
}
<form id="userForm">
<div id="updateAjax">
#if (string.IsNullOrWhiteSpace(ViewBag.MessageResult) == false)
{
<div class="#ViewBag.cssClass">
#Html.Label(ViewBag.MessageResult as string)
</div>
<br />
}
<table class="table" cellspacing="0">
#foreach (VwUser Item in Model)
{
<tr class="#(Item.IsActive ? "tRow" : "Disable-tRow")">
<td class="tbody">
<input type="checkbox" id="#Item.Id" name="selected" value="#Item.FullName"/></td>
<td class="tbody">#Item.FullName</td>
<td class="tbody">#Item.Post</td>
<td class="tbody">#Item.Education</td>
</tr>
}
</table>
</div>
<br />
<br />
<div class="btnContainer">
delete
<br />
<br />
</div>
<script>
$(function () {
// function for delet info and update #updateAjax div
$("#DeleteUser").click(function (event) {
var list = [];
$('#userForm input:checked').each(function () {
list.push(this.id);
});
$.ajax({
url: '#Url.Action("DeleteUser", "UserManagement")',
type: 'POST',
contentType: 'application/json; charset=utf-8',
dataType: "html",
traditional: true,
data: JSON.stringify(list),
success: function (data, textStatus, jqXHR) {
$('#updateAjax').html(data);
// window.location.reload()
},
error: function (data) {
//$('#updateAjax').html(data);
window.location.reload()
}
}); //end ajax
});});
</script>
</form>
this my controller code
public ActionResult View1()
{
ViewBag.PageTittle = "user list";
ViewBag.FormTittle = "user list";
SetUserManagement();
var Result = userManagement.SearchUsers(null);
if (Result.Mode == Common.Extensions.ActionResultMode.Successfully)
{
return View(Result.Data);
}
else
{
return View(new VwUser());
}
}
public ActionResult DeleteUser(string[] userId)
{
SetUserManagement();
string message = "", CssClass = ""; ;
foreach (string item in userId)
{
//TODO:show Message
var Result = userManagement.DeleteUser(int.Parse(item));
if (Result.Mode != Common.Extensions.ActionResultMode.Successfully)
{
var messageResult = XmlReader.FindMessagekey(Result.Mode.ToString());
message += messageResult.MessageContent + "<br/>";
CssClass = messageResult.cssClass;
}
}
if (string.IsNullOrEmpty(message))
{
SetMessage(Common.Extensions.ActionResultMode.Successfully.ToString());
}
else
{
ViewBag.MessageResult = message;
ViewBag.cssClass = CssClass;
}
//
{
var Result = userManagement.SearchUsers(null);
if (Result.Mode == Common.Extensions.ActionResultMode.Successfully)
{
return View("~/Views/UserManagement/View1.cshtml", Result.Data);
}
else
{
return View("~/Views/UserManagement/View1.cshtml", new VwUser());
}
}
}
It looks to me that your view ViewUserList.cshtml is using a Layout that would either be set through Layout or through the _ViewStart.cshtml file. Make sure you're not using any of these.
For disabling the use of your Layout, you could take a look at this question. Or just set Layout = null

Resources