How to use star rating plugin in MVC 4 application? - ajax

I want to use this star rating plugin in my MVC 4 application.
I have Rating table like this:
public class Rating
{
public int FromUserId { get; set; }
public int ToProductId { get; set; }
public int RateValue { get; set; }
}
I have an action like this:
public ActionResult SubmitRating(int fromUserId, int toProductId , int rateValue )
{
return View();
}
FromUserId is #WebSecurity.CurrentUserId and
ToProductId is Model.Id
I have problem with ajax. I need to send RateValue to action.
How can I send selected value to SubmitRating action in controller and reverse, to send back an answer from controller to view (to show selected value, to show any message to user etc.) ?
This does not work. How to write ajax code here?
$(function(){
$('#star-rating').rating(function(vote, event){
$.ajax({
url: "#Url.Action("SubmitRating", "MyController")",
type: "GET",
data: {rateValue : vote},
});
});
});

Let's assume some things:
your HTML has the product id:
<div id="star-rating" data-pid="#Model.Id">
<input type="radio" name="example" class="rating" value="1" />
<input type="radio" name="example" class="rating" value="2" />
<input type="radio" name="example" class="rating" value="3" />
<input type="radio" name="example" class="rating" value="4" />
<input type="radio" name="example" class="rating" value="5" />
</div>
so you can have a list of products instead only one product per page.
It's not a security practice to pass the user id if that's the same as the current logged in one, you could simple fetch the userid from the current session., so we would have in our controller:
public class ServicesController : Controller
{
public ActionResult RateProduct(int id, int rate)
{
int userId = WebSecurity.CurrentUserId;
bool success = false;
string error = "";
try
{
success = db.RegisterProductVote(userId, id, rate);
}
catch (System.Exception ex)
{
// get last error
if (ex.InnerException != null)
while (ex.InnerException != null)
ex = ex.InnerException;
error = ex.Message;
}
return Json(new { error = error, success = success }, JsonRequestBehavior.AllowGet);
}
}
this way you can easily call your rate like:
<script>
$(function () {
$('#star-rating').rating(function (vote, event) {
var anchor = $(event.currentTarget),
pid = anchor.closest(".ratting-item").data("pid"),
url = '#Url.Action("RateProduct", "Services")';
// show a loading div that would have a animated gif
$(".loading").show();
$.ajax({
url: url,
type: "GET",
data: { rate: vote, id: pid },
success: function (data) {
if (data.success) {
// all went well, here you can say Thank you
}
else {
// There must be an Exception error, let's show it
}
},
error: function (err) {
// the call thrown an error
},
complete: function () {
$(".loading").hide();
}
});
});
});
</script>
updated
$(this) does not return the correct element, so we need to use the event property that is passed along the call:
So we need to change to this:
var anchor = $(event.currentTarget),
pid = anchor.closest(".ratting-item").data("pid"),
url = '#Url.Action("RateProduct", "Services")';
a simple console.log($(this)) and then console.log(event); would tell you that, plus, if you fire Fiddler, you will see what's missing as well seeing the error on the returned call.
Project example on GIT
Here's the source code of this project working: https://github.com/balexandre/Stackoverflow-Question-14014091

Related

Razor not printing Values to screen after ASP 3.1 RazorPages AJAX Post Updates Model

Hello I am updating a model with an AJAX call on the event of a dropdown selection.
The model is updated and when I step through the below razor loop the values exist.
However nothing inside the #if statement prints to the screen, not even the H2.
The div is just empty... Thoughts?
#if (Model.FieldsRequiredOnStart != null)
{
foreach (var item in Model.FieldsRequiredOnStart)
{
for (int i = 0; i < #item.Inputs.Count(); i++)
{
<h2>Fields Required on Start</h2>
var x = #item.Inputs[i];
<span>#x.Name</span>
<input placeholder="#x.Name" maxlength="#x.MaxSize" type="#x.InputType"> <input />
}
}
}
function onSelect(e) {
let id = $("#wfDropdown").data("kendoDropDownList").value()
if (e.item) {
$('#wfDefId').val(id)
} else {
$('#wfDefId').val(id)
}
$.ajax({
type: 'Post',
url: '/CreateNewWorkflow?handler=RequiredInputs',
beforeSend: function (xhr) {
xhr.setRequestHeader("XSRF-TOKEN",
$('input:hidden[name="__RequestVerificationToken"]').val());
},
data: { Id: id },
success: function () {
}
});
}
EDIT ON SUCCESS:
I ended up using the Partial View solution. My issue was I was not sending a refreshed model when I had previously tried the partial way. The Second answer is also valid. Gotcha: If you make a partial be sure to remove the #Page reference at the top or you will get Model is null errors.
Also worth noting the C# Syntax I had to use was slightly different than what is provided in the answer to return the Partial view..
public ActionResult OnPostRequiredInputs(int id)
{
//DO STUFF
//Refresh Model to pass to partial
IEnumerable<Razor.PageModels.CreateWorkflowNames> namelist = da.GetWfDefVersionNameAndIds();
var freshModel = new CreateNewWorkflowModel(_cache, _mapper, _wlog, _workflowFactory, _configuration)
{
FieldsRequiredOnStart = entityDefinitionFieldsList,
CreateWorkflowModel = namelist
};
return Partial("/Pages/_CreateNewWorkflowRequiredFieldsPartial.cshtml", freshModel);
}
Assuming your CreateNewWorkflow controller action returns a model rehydrated with the new data, you should be able to set that new data in the onSuccess callback of your ajax request.
I'd do this to accomplish the result.
Create partial view for the razor we're gonna need to refresh.
//Filename: YourView.cshtml
<div id="partialWrapper"></div>
//File name: _YourPartialView.cshtml
#if (Model.FieldsRequiredOnStart != null)
{
foreach (var item in Model.FieldsRequiredOnStart)
{
for (int i = 0; i < #item.Inputs.Count(); i++)
{
<h2>Fields Required on Start</h2>
var x = #item.Inputs[i];
<span>#x.Name</span>
<input placeholder="#x.Name" maxlength="#x.MaxSize" type="#x.InputType"> <input />
}
}
}
Make sure your controller action returns a partial view.
public IActionResult<YourModelClass> CreateNewWorkflow(YourRequestClass request) {
//your logic
//...
var rehydratedModel = new YourModelClass(); //actually fill this with data
return PartialView(rehydratedModel);
}
Set the partial view result to your wrapper div in the onSuccess call back.
function onSelect(e) {
let id = $("#wfDropdown").data("kendoDropDownList").value()
if (e.item) {
$('#wfDefId').val(id)
} else {
$('#wfDefId').val(id)
}
$.ajax({
type: 'Post',
url: '/CreateNewWorkflow?handler=RequiredInputs',
beforeSend: function (xhr) {
xhr.setRequestHeader("XSRF-TOKEN",
$('input:hidden[name="__RequestVerificationToken"]').val());
},
data: { Id: id },
success: function (data) { //data represents your partial view
$('#partialWrapper').html(data) //set partial view
}
});
That is a pretty typical flow of how you refresh razor pages with ajax.
Razor not printing Values to screen after ASP 3.1 RazorPages AJAX Post Updates Model, The div is just empty
The issue is related to the Ajax success function, according to your code, we can see that you didn't do anything to update the page with the latest data.
Generally, after getting the latest data in the success function, we could use JQuery to find the page elements and bind the latest data or populate the new page element to replace the old data. You could refer to the following sample code:
<select id="ddl1" asp-for="CategoryId" asp-items="Model.Categories">
<option value="">Select Category</option>
</select>
<h4>SubCategories</h4>
#if (Model.SubCategories != null)
{
<table >
<tr><th>SubCategoryId</th><th>CategoryId</th><th>SubCategoryName</th></tr>
<tbody id="tbody">
#foreach (var item in Model.SubCategories)
{
<tr>
<td>#item.SubCategoryId</td>
<td>#item.CategoryId</td>
<td>#item.SubCategoryName</td>
</tr>
}
</tbody>
</table>
}
Code in the cshtml.cs file:
private ICategoryService _categoryService;
public DDLpageModel(ICategoryService categoryService)
{
_categoryService = categoryService;
}
[BindProperty(SupportsGet = true)]
public int CategoryId { get; set; }
public int SubCategoryId { get; set; }
public SelectList Categories { get; set; }
public List<SubCategory> SubCategories { get; set; }
public void OnGet()
{
Categories = new SelectList(_categoryService.GetCategories(), nameof(Category.CategoryId), nameof(Category.CategoryName));
SubCategories = _categoryService.GetSubCategories(1).ToList();
}
public JsonResult OnGetSubCategories()
{
return new JsonResult(_categoryService.GetSubCategories(CategoryId));
}
Then, in the Ajax success function, find the element and set the value or dynamic add page elements with the latest data and replace the old one.
#section scripts{
<script>
$(function () {
$("#ddl1").on("change", function () {
var categoryId = $(this).val();
//method 1: using JQuery Ajax get the latest data and update the main page content
$.ajax({
url: `?handler=SubCategories&categoryId=${categoryId}`,
contentType: 'application/json; charset=utf-8',
type: 'get',
dataType: 'json',
success: function (data) {
$("#tbody").html("");
//loop through the data and append new data to the tbody
$.each(data, function (i, item) {
$("#tbody").append("<tr><td>" + item.subCategoryId + "</td><td>" + item.categoryId + "</td><td>" + item.subCategoryName + "</td></tr>");
});
}
});
});
});
</script>
}
Besides, you could also create a Partial page (for example: _SubCategories.cshtml):
#model List<SubCategory>
<table class="table table-striped">
<tr><th>SubCategoryId</th><th>CategoryId</th><th>SubCategoryName</th></tr>
<tbody id="tbody">
#foreach (var item in Model)
{
<tr>
<td>#item.SubCategoryId</td>
<td>#item.CategoryId</td>
<td>#item.SubCategoryName</td>
</tr>
}
</tbody>
</table>
In the main page .cshtml.cs file, add the following handler:
public PartialViewResult OnGetSubcategoryPartial()
{
var subcategories = _categoryService.GetSubCategories(CategoryId).ToList();
return Partial("_SubCategories", subcategories);
}
Then, using JQuery Ajax to call the above handler and load the partial page:
<h2>Using Partial Page</h2>
<select id="ddl2" asp-for="CategoryId" asp-items="Model.Categories">
<option value="">Select Category</option>
</select>
<div id="output">
</div>
#section scripts{
<script>
$(function () {
$("#ddl2").on("change", function () {
var categoryId = $(this).val();
$.ajax({
url: `?handler=SubcategoryPartial&categoryId=${categoryId}`,
contentType: 'application/html; charset=utf-8',
type: 'get',
dataType: 'html',
success: function (result) {
$("#output").html("");
$("#output").append(result);
}
});
});
});
</script>
}
The screenshot like this:

Ajax call not working in foreach loop in MVC

I'm dynamically adding data to the database using AJAX and displaying them using foreach loop in MVC, I have also added a button to remove the those data using ajax call.
HTML/MVC code:
<div id="divaddrules" class="form-group row">
#try
{
foreach (var item in ViewBag.AdditionalRules)
{
<div class="col-sm-10">
<p style="font-size:large">#item.AdditionalDesc</p>
</div>
<div class="col-sm-2">
<input type="button" onclick="Removeinput(#item.id)" class="text-dark" style="border:none; background-color:transparent" value="X" />
</div>
}
}
catch (Exception ex){ }
</div>
Now when I click on Remove button it call the following JS code:
function Removeinput(id) {
var datas = {};
datas.addId = id
$.ajax({
url: "/Rooms/RemoveAdditionalRules",
type: "GET",
data: datas,
success: function (result) {
alert(result.id);
$("#divaddrules").load(window.location.href + " #divaddrules");
},
error: function (result) {
alert("Error: " + result.status);
}
});
}
and its passing to this controller:
[HttpGet]
[Authorize]
public ActionResult RemoveAdditionalRules(int addId)
{
HouseRules rules = db.HouseRules.Find(addId);
db.HouseRules.Remove(rules);
db.SaveChanges();
return Json(JsonRequestBehavior.AllowGet);
}
I'm getting 500 error on ajax call error.
Can anyone tell me where I'm doing it wrong? Please.. I'm stuck here.
Update:
Attached screenshot: Debug Screenshot
Write your Removeinput function as follows:
function Removeinput(id) {
$.ajax({
url: "/Rooms/RemoveAdditionalRules",
type: "GET",
data: { addId : id},
success: function (response) {
alert(response);
$("#divaddrules").load(window.location.href + " #divaddrules");
},
error: function (result) {
alert("Error: " + result.status);
}
});
}
Then in the controller method:
[HttpGet]
[Authorize]
public ActionResult RemoveAdditionalRules(int addId)
{
AdditionalRules rules = db.AdditionalRules.Find(addId); // Here was the problem. He was pointing to the wrong table that has fixed over team viewer.
db.AdditionalRules.Remove(rules);
db.SaveChanges();
return Json(addId,JsonRequestBehavior.AllowGet);
}
the problem it is missing values on db, in the image you ask to id 25 but return null and you try to remove a item passing null value.
so in your case you need to validate before remove or fix the missing data:
[HttpGet]
[Authorize]
public ActionResult RemoveAdditionalRules(int addId)
{
HouseRules rules = db.HouseRules.Find(addId);
If(rules == null)
{
//return error msg.
return Json(JsonRequestBehavior.AllowGet);
}
db.HouseRules.Remove(rules);
db.SaveChanges();
return Json(JsonRequestBehavior.AllowGet);
}
make your input type submit, may this was helpful
function deleterelation(id) {
debugger;
if (id > 0)
$.ajax({
url: "/Relations/Delete/" + id,
type: "get",
datatype: "json",
data: { id: id },
success: function (response) {
debugger;
if (response != null) {
$("#txtDName").text(response.name);
$("#DRelationId").val(response.id);
$("#DeleteRelation").modal("show");
}
},
error: function (response) {
$("#DeleteRelationLoading").hide();
$("#DeleteRelation_btn_cancel").show();
$("#DeleteRelation_btn_save").show();
}
});
else
toastr.error("Something went wrong");
}
<input type="submit" onclick="Removeinput(#item.id)" class="text-dark" style="border:none; background-color:transparent" value="X" />
if this not work plz let me know

Like button in MVC using 'Ajax.Beginform()' not able to display total likes on page

I am beginner in MVC and Ajax development and want a like button in my web, which should work like this: if the user clicks on it total likes will be incremented by 1 and if the user clicks it again (dislike) then it will decremented by 1. What I have done so far is this:
Here's the Model:
public class Like
{
public int Id { get; set; }
public virtual Video Video { get; set; }
public int VideoID { get; set; }
public string UserId { get; set; }
public virtual ApplicationUser ApplicationUser { get; set; }
}
Here is the Controller:
Post Method
[HttpPost]
public ActionResult Like(int Id, Like like)
{
if (ModelState.IsValid && User.Identity.IsAuthenticated == true)
{
like.Video = storeDB.Videos.Find(Id);
like.UserId = User.Identity.GetUserId();
var userlike = storeDB.Likes.Where(l => l.UserId == like.UserId && l.VideoID == Id);
if (userlike.Count() == 0)
{
storeDB.Likes.Add(like);
storeDB.SaveChanges();
}
else if (userlike.Count() == 1)
{
var likeDel = storeDB.Likes.FirstOrDefault(l => l.UserId == like.UserId && l.VideoID == Id);
storeDB.Likes.Remove(likeDel);
storeDB.SaveChanges();
}
List<Like> videoLikes = storeDB.Likes.Where(v => v.VideoID == Id).ToList();
int nooflikes = videoLikes.Count();
ViewBag.noLikes = nooflikes;
return Json(ViewBag.noLikes, JsonRequestBehavior.AllowGet);
}
else
{
ViewBag.Message = "Login to like this video";
return PartialView("Like", ViewBag.noLikes);
}
This is the Get method of Like:
public ActionResult Like(int id)
{
List<Like> videoLikes = storeDB.Likes.Where(v => v.VideoID == id).ToList();
int nooflikes = videoLikes.Count();
ViewBag.noLikes = nooflikes;
return Json(ViewBag.noLikes, JsonRequestBehavior.AllowGet);
}
and I have created a Partial View for this:
#if (ViewBag.Message != null)
{
<script>
$(document).ready(function () {
alert('#ViewBag.Message');
});
</script>
}
//to display total likes
<input type="text" id="likes" name="likes" value='#ViewBag.noLikes' readonly="readonly" style="border:none; background-color:transparent; width:20px" /><span style="color:black">likes</span>
and this is the main view in which I am using Ajax.BeginForm()
#using (Ajax.BeginForm("Like", "VOD", new { Id = Model.Id },
new AjaxOptions
{
HttpMethod = "Post",
InsertionMode = InsertionMode.Replace,
UpdateTargetId = "likecount"
}))
{
<button type="submit" id="like" value="Like" class=" btn btn-primary btn-xs"> Like <span class="glyphicon glyphicon-thumbs-up" aria-hidden="true"></span> </button>
}
<span id="likecount">
#Html.Partial("Like", new Models.Like())
</span>
Now the issue is that when the page is first loaded it is not displaying total likes, and when I click on like button it returns 1 and when I click like button again it returns 0 but when I refresh the page or when I post back to another page total likes again disappear.
Can anybody help me?
Instead of doing so much code you can do above functionality in simple way.
You will required following to do so,
2 Action Methods,
1. Increment Like Count.
2. Decrease Like Count.
2 Buttons on web page
1. Like Button (Initially visible)
2. DisLike Button (Initially Invisible)
you can create a ajax request on both buttons something like bellow,
$("#btnLike").click(function () {
$.ajax({
type: "POST",
url: "Controller/LikeAction",
data: { /* Your Data */ };
success: function (result) {
// Hide Like Button & Show Dislike Button
},
error: function (error) {
alert("error = " + error);
}
});
});
Same way you can create ajax request for dislike button also. You just need to hide and show buttons.

MVC 3 razor - maintain checkbox values between page requests

I have a page with checkboxes which are used to filter a webgrid.
To give my question some context by unchecking a checkbox the data will be filtered to show fewer results in my webgrid by using ajax request. But once I click on the numbers below the webgrid to cycle through the next set of records in the grid I lose the current state of my checkboxes. This is because I am calling my ActionResult method again which is loading the page again.
So how do I maintain those checkbox values between page loads?
This is my view
#model IEnumerable<UserManager.Models.vw_UserManager_Model>
#*#model UserManager.Models.vw_UserManager_Model
*#
#{
ViewBag.Title = "User Manager Dashboard";
}
#Html.ActionLink("Create New User", "CreateUser")
<div class="webgrid-filter">
<b>#Html.Label("Select a filter: ")</b>
<br />
#Html.Label("Toggle ALF Intelligence users:")
<input name="User logged in" type="checkbox" onclick="filterGrid('#Url.Action("Index", "UserManager")')" id="chkFilterAlfIntell" checked="checked" />
#Html.Label("Toggle ALF Connect users:")
<input name="User logged in" type="checkbox" onclick="filterGrid('#Url.Action("Index", "UserManager")')" id="chkFilterAlfConn" checked="checked"/>
#Html.Label("Toggle BRAD users:")
<input name="User logged in" type="checkbox" onclick="filterGrid('#Url.Action("Index", "UserManager")')" id="chkFilterBrad" checked="checked"/>
</div>
<div id="webgrid-wrapper">
#Html.Partial("~/Views/Partial/_WebGridUserManager.cshtml", Model)
</div>
<br />
<script type="text/javascript">
$(document).ready(function () {
// Disable checkboxs where a user is not active.
$(".webgrid-wrapper input:not(:checked)").attr("disabled", "disabled");
// Style tables.
function jQueryUIStyling() {
$('input:button, input:submit').button();
$('.webgrid-wrapper').addClass('ui-grid ui-widget ui-widget-content ui-corner-all');
$('.webgrid-title').addClass('ui-grid-header ui-widget-header ui-corner-top');
jQueryTableStyling();
} // end of jQueryUIStyling
function jQueryTableStyling() {
$('.webgrid').addClass('ui-grid-content ui-widget-content');
$('.webgrid-header').addClass('ui-state-default');
$('.webgrid-footer').addClass('ui-grid-footer ui-widget-header ui-corner-bottom ui-helper-clearfix');
} // end of jQueryTableStyling
});
</script>
<script type="text/javascript">
function filterGrid(url) {
var filters = getFilterVals();
// console.log(filters);
$.ajax({
url: url,
type: "POST",
async: true,
dataType: "html",
data: "alfConnect=" + filters.alfConnect + "&" + "alfIntelligence=" + filters.alfIntelligence + "&" + "brad=" + filters.brad,
success: function (data) {
$('#webgrid-wrapper').empty().html(data);
// $('#webgrid-wrapper').html(data);
}
});
}
function getFilterVals() {
filters = new Object();
if ($('.webgrid-filter #chkFilterAlfIntell').is(':checked')) {
filters.alfIntelligence = 1;
}
else {
filters.alfIntelligence = 0;
}
if ($('.webgrid-filter #chkFilterAlfConn').is(':checked')) {
filters.alfConnect = 1;
}
else {
filters.alfConnect = 0;
}
if ($('.webgrid-filter #chkFilterBrad').is(':checked')) {
filters.brad = 1;
}
else {
filters.brad = 0;
}
return filters;
}
function logUserOff(url) {
var answer = confirm('Are you sure you want to save this data?')
if (answer) {
// alert(url + ": " + value);
$.ajax({
url: url,
type: "POST"
// data: value
}).done(function () {
$(this).addClass("done");
});
return true;
}
else {
return false;
}
};
</script>
In div class webgrid filter you can see the checkboxes which I want to maintain the values of.
My actionResult for this view
public ActionResult Index()
{
try
{
var model = new UserManagerTestEntities().vw_UserManager_Model;
//var model = new UserManager.Models.vw_UserManager_Model();
return View(model.ToList());
}
catch (Exception ex)
{
return View(ViewBag);
}
}
Does anyone have suggestions? Thanks!
Instead of doing action on your controller, maybe you could: as click action on checkbox call javascript function which at the end would make ajax call.

Cannot bind JSon with MVC 3 controller data using KnockoutJS

I am new to javascript and MVC 3. I am developing a sample application to get familiar with KnockoutJs.
I am passing a c# object with some properties to a controller. Than this object is passed to the View serialized as JSon. Then I am using the data with Knockout in my view and want to return this data back to the server. But the binding with the the server data fails for on of my properties.
Here is my code:
Model:
public class FranchiseInfo
{
public string FullName { get; set; }
public string ShortName { get; set; }
public List<string> ServerIps = new List<string>();
}
Controller with sample data returning JSon to the View:
public JsonResult Data()
{
FranchiseInfo franchiseInfo = new FranchiseInfo();
franchiseInfo.FullName = "PokerWorld";
franchiseInfo.ShortName = "PW";
franchiseInfo.ServerIps.Add("192.111.1.3");
franchiseInfo.ServerIps.Add("192.112.1.4");
return Json(franchiseInfo, JsonRequestBehavior.AllowGet);
}
Javascript file using knockout:
$(function () {
function viewModel() {
var self = this;
self.FullName = ko.observable();
self.ShortName = ko.observable();
self.optionValues = ko.observableArray([]);
self.ServerIps = ko.observableArray([]);
$.getJSON("Home/Data", function (data) {
self.FullName(data.FullName);
self.ShortName(data.ShortName);
self.optionValues([data.FullName, data.ShortName]);
for (var i = 0; i < data.ServerIps.length; i++) {
self.ServerIps.push({ name: ko.observable(data.ServerIps[i]) });
}
});
self.addIp = function () {
self.ServerIps.push({ name: ko.observable("0.0.0") });
}
self.showIps = function () {
alert(self.ServerIps[name]);
}
self.save = function () {
$.ajax({
url: "Home/Save",
type: "post",
data: ko.toJSON({ FullName: self.FullName, ShortName: self.ShortName, ServerIps: self.ServerIp }),
contentType: "application/json",
success: function (result) { alert("result") }
});
}
};
ko.applyBindings(new viewModel);
View:
Full Name:
<span data-bind="text: FullName"></span>
<input data-bind="value: FullName" />
</div>
<div>
Short Name:
<span data-bind="text: ShortName"></span>
</div>
<select data-bind="options: optionValues"></select>
<div data-bind="foreach: ServerIps">
Name:
<input data-bind="value: name" />
<span data-bind="text: name" />
</div>
<div data-bind="text: ko.toJSON(ServerIps)"></div>
<button data-bind="click: addIp">Add IP</button>
<button data-bind="click: save">Save</button>
When Save button is clicked the data is sent to the server in Json format:
Here is the controller:
public JsonResult Save(FranchiseInfo franchiseInfo)
{
//some data here
//return Json result
}
Full name and Short name properties bind correctly with the c# model when I am sending them in Json format back to the server but the ServerIps property which is an array cannot bind. I think because it is in the format { name: ip} and the model property ServerIps is of type List. How can I fix this ? Any help with working example will be appreciated. Thanks.
I had the same problem in Java Spring.
We solved it by serializing the ViewModel as a request string.
We wrote the function ourselves (although you might want to check if the 'value' is an array and go a bit recursive):
function serializeViewModelToPost(dataString) {
var data = ko.toJS(dataString);
var returnValue = '';
$.each(data, function (key, value) {
returnValue += key + '=' + value + '&';
});
return returnValue;
}
Another option is to parse it serverside:
link
UPDATE:
self.save = function () {
$.ajax({
url: "Home/Save",
type: "post",
data: serializeViewModelToPost(this)),
success: function (result) { alert("result") }
});
You still need to edit the serialize function to check for arrays.

Resources