Update main viewmodel when partial view updated via ajax post - asp.net-mvc

I am trying to get the viewmodel on the page to update when a partial view is updated via an ajax post. The partial view updates correctly but on the next update call the model seesm to have reverted back to the orginal state.
The partial view is a table and I am either adding or deleting a row. The codde is included below any ideas as to how this can be done.
page code is
<div class="filters">
<fieldset class="source">
<legend>Search Attributes</legend>
<div id="attributes-filter">
#Html.Partial("_EditSearchQuery")
</div>
</fieldset>
</div>
<div>
<a id="addRowLink" class="add-row-link" href="#">Add new clause</a>
</div>
</div>
</div>
-- partial view is
<table id="searchClauses" class="clauses">
<tbody>
<tr class="header">
<td class="add-remove"></td>
<td class="logical">And/Or</td>
<td class="field">Field</td>
<td class="operator">Operator</td>
<td class="value">Value</td>
</tr>
#foreach (SearchClause item in Model.searchClauses)
{
<tr class="clause clause-row" id=#item.RowID>
<td class="add-remove">
<a href="#" title="Remove this filter line" id=#item.ID >Delete</a>
</td>
<td>
#Html.DropDownListFor(modelitem => item.logicalTypeValue, new SelectList(item.logicalTypeList, "Value", "Text", "Selected"), new { style = "width: 60px" })
</td>
<td>
#Html.DropDownListFor(modelitem => item.fieldListValue, new SelectList(item.fieldList, "Value", "Text", "Selected"))
</td>
<td>
#Html.DropDownListFor(modelitem => item.operatorListValue, new SelectList(item.operatorList, "Value", "Text", "Selected"), new { style = "width: 60px" })
</td>
<td>
#Html.TextBoxFor(modelitem => item.valuesList[0], new { style = "width: 130px" })
</td>
</tr>
}
</tbody>
-- script
<script type="text/javascript">
$(function () {
// Save quiz view - new or existing.
$("#attributes-filter").on("click", "a", function () { // A jQuery delegated event - #EditQuiz is always present, a.SaveQuiz only exists when the _ElearningQuiz partial view is loaded.
deleteRow($(this).attr("id"));
});
function deleteRow (id) {
var rowData = {
'id': id,
'model' : #Html.Raw(Json.Encode(Model))
};
$.ajax({
url: "/Participant/DeleteClause",
type: "POST",
data: JSON.stringify(rowData),
contentType: "application/json; charset=utf-8",
success: function (result) {
$("#attributes-filter").html(result);
},
error: function (jqXHR, textStatus, errorThrown) {
alert("Status: " + textStatus + " Error: " + errorThrown);
}
});
};
$("#addRowLink").click(function () {
var model = #Html.Raw(Json.Encode(Model))
$.ajax({
url: "/Participant/AddClause",
type: "POST",
data: JSON.stringify(model),
contentType: "application/json; charset=utf-8",
success: function (result) {
$("#attributes-filter").html(result);
},
error: function (jqXHR, textStatus, errorThrown) {
alert("Status: " + textStatus + " Error: " + errorThrown);
}
});
});
});
</script>
-- controllers
[HttpPost]
public ActionResult AddClause(DynamicSearchModel model)
{
int campaignId = SessionManager.CampaignId;
int clientId = SessionManager.ClientId;
var newClause = _participantServiceClient.NewSearchClause(campaignId, clientId, 2);
newClause.ID = model.searchClauses.Count + 1;
model.searchClauses.Add(newClause);
return PartialView("_EditSearchQuery", model);
}
[HttpPost]
public ActionResult DeleteClause(string id, DynamicSearchModel model)
{
int _id = int.Parse(id);
model.searchClauses.RemoveAt(_id - 1);
return PartialView("_EditSearchQuery", model);
}

Related

Pass Object Parameter from javascript\ajax to function in Controller

I have a table that i want to be able to update the status of each line that checkbox is on
(see attached screenshot)
The checkbox propery in the Model is Not Mapped to the database ([NotMapped])
Html:
<div class="row">
<div class="col-12 text-right">
<button class="btn btn-primary" onclick="ApproveStatus()">Approve Checked Lines</button>
</div>
</div>
javaScript:
#section Scripts{
<script type="text/javascript">
function ApproveStatus() {
var pdata = new FormData();
swal({
title: "Are you sure?",
text: "Once Updated, you will not be able to Undo this",
icon: "warning",
buttons: true,
dangerMode: true,
})
.then((willDelete) => {
if (willDelete) {
$.ajax({
url: "PaymentHistory/ApproveStatus",
type: "POST",
data: pdata,
processData: false,
contentType: false,
success: function (data) {
swal("Success!", {
icon: "success",
});
}
});
setTimeout(function () {
location.reload()
}, 100);
} else {
swal("Nothing Changed!");
}
});
}
</script>
}
And in the Controller i have the function (haven't written the logic yet)
[HttpPost]
public IActionResult ApproveStatus()
{
}
table in html:
<table id="tblData" class="table table-striped table-bordered" style="width:100%">
<thead class="thead-dark">
<tr class="table-info">
<th>Address</th>
<th>Payment Type</th>
<th>Amount</th>
<th>Payment Date</th>
<th>Status</th>
<th></th>
</thead>
#foreach (PaymentHistory paymentHistory in Model)
{
<tr>
<td>#ViewBag.getPaymentAddress(paymentHistory.SentFromAddressId).ToString()</td> <td>#ViewBag.getPaymentType(paymentHistory.SentFromAddressId).ToString()</td>
<td>#paymentHistory.Amount$</td>
<td>#paymentHistory.PayDate</td>
<td>#paymentHistory.Status</td>
#if (paymentHistory.Status != "Approved")
{
<td>
<div class="text-center">
<input type="checkbox" asp-for="#paymentHistory.isChecked"/>
</div>
</td>
}
else
{
<td></td>
}
</tr>
}
</table>
My only issue is that i want to pass the Object from the View (that contains the lines and status of the checkbox) to the function in the controller as a parameter,
Any ideas how can i do this?
Thank you
i want to pass the Object from the View (that contains the lines and status of the checkbox) to the function in the controller as a parameter, Any ideas how can i do this?
To achieve your requirement, you can try to add a hidden field for SentFromAddressId field, like below.
<td>
<div class="text-center">
<input type="hidden" asp-for="#paymentHistory.SentFromAddressId" />
<input type="checkbox" asp-for="#paymentHistory.isChecked" />
</div>
</td>
then you can get the sentFromAddressId of each checked row and populate it in form data object.
var pdata = new FormData();
$("input[name='paymentHistory.isChecked']:checked").each(function (index, el) {
var sentFromAddressId = $(this).siblings("input[type='hidden']").val();
pdata.append("Ids", sentFromAddressId);
})
and post the data to action method with following code snippet.
$.ajax({
type: 'POST',
url: '/PaymentHistory/ApproveStatus',
data: pdata,
processData: false,
contentType: false,
datatype: 'json',
success: function (res) {
//...
}
});
ApproveStatus action method
public IActionResult ApproveStatus(int[] Ids)
{
//code logic here
//update corresponding record based on id within Ids
Get all checked checkboxes id in an array, use that array to update table

KnockoutJS in MVC DataTable Delete Function

I have followed a tutorial that I found at http://www.dotnetcurry.com/aspnet-mvc/933/knockoutjs-aspnet-mvc-tutorial-beginner. The tutorial is great and covers add and update however there are no click handlers included for delete or cancelling the update.
I tried to follow the same pattern the author provided for saving data and I created a function to delete, however this does not work.
function deleteData(currentData) {
var postUrl = "";
var submitData = {
concerns_id: currentData.concerns_id(),
concerns_description: currentData.concerns_description(),
};
if (currentData.concerns_id > 0) {
postUrl = "/concerns/delete"
}
$.ajax({
type: "POST",
contentType: "application/json",
url: postUrl,
data: JSON.stringify(submitData)
}).done(function (id) {
currentData.concerns_id(id);
}).error(function (ex) {
alert("ERROR Deleting");
})
};
This is the table:
<table class="table">
<tr>
<th>concerns_id</th>
<th>concerns_description</th>
<th></th>
</tr>
<tbody data-bind="foreach: ConcernCollection">
<tr data-bind="template: { name: Mode, data: $data }"></tr>
</tbody>
</table>
The Templates:
<script type="text/html" id="display">
<td data-bind="text: concerns_id"></td>
<td data-bind="text: concerns_description"></td>
<td>
<button class="btn btn-success kout-edit">Edit</button>
<button class="btn btn-danger kout-delete">Delete</button>
</td>
</script>
<script type="text/html" id="edit">
<td><input type="text" data-bind="value: concerns_id " /></td>
<td><input type="text" data-bind="value: concerns_description" /></td>
<td>
<button class="btn btn-success kout-update">Update</button>
<button class="btn btn-danger kout-cancel">Cancel</button>
</td>
</script>
Full JS without the Delete Function that I tied to add:
$(document).ready(function () {
$.ajax({
type: "GET",
url: "/concerns/GetConcerns",
}).done(function (data) {
$(data).each(function (index, element) {
var mappedItem =
{
concerns_id: ko.observable(element.concerns_id),
concerns_description: ko.observable(element.concerns_description),
Mode: ko.observable("display")
};
viewModel.ConcernCollection.push(mappedItem);
});
ko.applyBindings(viewModel);
}).error(function (ex) {
alert("Error");
});
$(document).on("click", ".kout-edit", null, function (ev) {
var current = ko.dataFor(this);
current.Mode("edit");
});
$(document).on("click", ".kout-update", null, function (ev) {
var current = ko.dataFor(this);
saveData(current);
current.Mode("display");
});
$(document).on("click", "#create", null, function (ev) {
var current = {
concerns_id: ko.observable(0),
concerns_description: ko.observable(),
Mode: ko.observable("edit")
}
viewModel.ConcernCollection.push(current);
});
function saveData(currentData) {
var postUrl = "";
var submitData = {
concerns_id: currentData.concerns_id(),
concerns_description: currentData.concerns_description(),
};
if (currentData.concerns_id && currentData.concerns_id() > 0) {
postUrl = "/concerns/Edit"
}
else {
postUrl = "/concerns/Create"
}
$.ajax({
type: "POST",
contentType: "application/json",
url: postUrl,
data: JSON.stringify(submitData)
}).done(function (id) {
currentData.concerns_id(id);
}).error(function (ex) {
alert("ERROR Saving");
})
}
});
Any help or guidance would be apprenticed this is my first time working with Knockout.js
Thanks,
I'm not gonna lie, your code is a little hard to follow. I really don't think you're getting the full knockout experience. I put together a tiny little demo to show you just how you can use knockout to add/remove items from a list and display them.
Knockout should be used for data-binding. You should honestly never need to use jQuery to attach listeners by class. That is how your code becomes spaghetti.
While your question doesn't ask it, I strongly recommend visiting http://learn.knockoutjs.com/ before continuing your tutorial much further.
I hope this helps!
function ViewModel() {
var self = this;
self.Items = ko.observableArray();
self.DeleteRow = function(row) {
// Your ajax call here
self.Items.remove(row);
}
self.AddRow = function() {
self.Items.push("Added Item at " + new Date());
}
self.LoadFakeData = function() {
// Put ajax calls here
for (i = 0; i < 10; i++) {
self.Items.push("Item " + i);
}
}
self.Load = function() {
self.LoadFakeData();
}
self.Load();
}
ko.applyBindings(new ViewModel())
<script src="https://cdnjs.cloudflare.com/ajax/libs/knockout/3.4.2/knockout-min.js"></script>
<div data-bind="foreach: Items">
<span data-bind="text: $data"></span>
<span data-bind="click: $parent.DeleteRow">X</span>
<br>
</div>
<hr>
<span data-bind="click: AddRow">Add Row</span>

Partial View Not Rendering inside div

So I was trying to follow this guide and the followup article.
But Before I started with the searching, sorting and filtering, I wanted to see if even the pages were working as intended.
Unfortunately they are not and I cant for the life of me figure it out why, I even went so far as to download his working example just to see if it was something with my browser. (To download his working example its at the top of the second article, I cant post more then 2 links)
Since his worked I compared his views, controllers and scripts side by side to mine and from what I can tell they mirror each other.
So I ended up copying my code somewhere else and pasted his into my project, changed the ActionLinks to reflect the naming conventions I used and left out the stuff I havent implemented yet (noted above). And it still do sent work.
When I run them side by side I get no errors in the console, they are loading the same scripts with the exception that I added jquery.unobstrusive-ajax.js as an attempt to correct it from searching for solutions, but it didnt help.
I have no idea what I'm doing wrong here :/
My Manage View - Correlates to his Home Index View
The only thing I really changed here is the action link
#{
ViewBag.Title = "Home Page";
Layout = null;
}
<!DOCTYPE html>
<html>
<head>
#Styles.Render("~/Content/css")
#Scripts.Render("~/bundles/modernizr")
#Scripts.Render("~/bundles/jquery")
#Scripts.Render("~/bundles/jqueryval")
#Scripts.Render("~/bundles/bootstrap")
<script src="~/Scripts/ModalDialog.js"></script>
<style>
.testClass {
font-size: xx-large;
text-transform: capitalize;
}
</style>
<title>
Complete example of MVC pagination, filtering and sortig inside patial view with edit in modal dialog
</title>
</head>
<body style="padding-top:0">
<table style="width:100%;" border="1" cellspacing="0" cellpadding="0">
<tr>
<td style="" colspan="2">
<div id="logo" style="height:70px; background-color:rgba(86, 111, 111, 1);font: 1.5em Georgia, Times New Roman, Times, serif;">
Complete example of MVC pagination, filtering and sortig inside patial view with edit in modal dialog
</div>
<div id="navigation" style="background-color:#a4c2c2">
HOME
</div>
</td>
</tr>
<tr style="height:600px">
<td style="width:200px;background-color: #a4c2c2; vertical-align:top; padding-top:10px; padding-left:10px">
<div>
<ul>
<li>
#Html.ActionLink("Manage Assets", "MasterDetail", "Assets", new { }, new { id = "btnCustomers", #class = "btn btn-default btn-xs" })
</li>
</ul>
</div>
</td>
<td>
<div id="contentFrame" style="width:100%; height:600px; padding-top:10px; padding-left:10px" />
</td>
</tr>
</table>
</body>
</html>
<script type="text/javascript">
$(function () {
$.ajaxSetup({cache : false})
$('#btnCustomers').click(function () {
$('#contentFrame').mask("waiting ...");
$('#contentFrame').load(this.href, function (response, status, xhr) {
$('#contentFrame').unmask("waiting ...");
});
return false;
});
});
</script>
My MasterDetail View - Correlates to his Customers Index view
My table is setup different because i havent done everything he has yet
#using PagedList.Mvc
#model PagedList.IPagedList<Furst_Alpha_2._0.Models.Quantities>
#{
Layout = null;
}
#Styles.Render("~/Content/css")
#Scripts.Render("~/bundles/modernizr")
#Scripts.Render("~/bundles/jquery")
#Scripts.Render("~/bundles/jqueryval")
#Scripts.Render("~/bundles/bootstrap")
<script src="~/Scripts/ModalDialog.js"></script>
<h2>Inventory Management</h2>
<p>
#Html.ActionLink("Create New", "_Create", new { id = -1 }, new { btnName = "btnCreate", #class = "btn btn-default btn-xs" })
</p>
<table class="table">
<tr>
<th>
Category
</th>
<th>
Make
</th>
<th>
Model
</th>
<th>
Type
</th>
<th>
Length
</th>
<th>
Width
</th>
<th>
Height
</th>
<th>
Weight
</th>
<th>
Description
</th>
<th>
Rental Price
</th>
<th>
Number Of Techs
</th>
<th>
Total
</th>
<th>
In User
</th>
<th>
Availability
</th>
<th></th>
</tr>
#foreach (var item in Model)
{
<tr>
<td>
#Html.DisplayFor(modelItem => item.Assets.Category.CategoryName)
</td>
<td>
#Html.DisplayFor(modelItem => item.Assets.Make.MakeName)
</td>
<td>
#Html.DisplayFor(modelItem => item.Assets.Model.ModelName)
</td>
<td>
#Html.DisplayFor(modelItem => item.Assets.Type.TypeName)
</td>
<td>
#Html.DisplayFor(modelItem => item.Assets.Length)
</td>
<td>
#Html.DisplayFor(modelItem => item.Assets.Width)
</td>
<td>
#Html.DisplayFor(modelItem => item.Assets.Height)
</td>
<td>
#Html.DisplayFor(modelItem => item.Assets.Weight)
</td>
<td>
#Html.DisplayFor(modelItem => item.Assets.Description)
</td>
<td>
#Html.DisplayFor(modelItem => item.Assets.RentalPrice)
</td>
<td>
#Html.DisplayFor(modelItem => item.Assets.NumTechsReq)
</td>
<td>
#Html.DisplayFor(modelItem => item.total)
</td>
<td>
#Html.DisplayFor(modelItem => item.InUse)
</td>
<td>
#Html.DisplayFor(modelItem => item.Availability)
</td>
<td>
#Html.ActionLink("Edit", "Edit", new { id = item.QuantityId }, new { btnName = "btnEdit", #class = "btn btn-default btn-xs" })
#Html.ActionLink("Delete", "Delete", new { id = item.QuantityId }, new { btnName = "btnDelete", #class = "btn btn-default btn-xs" })
</td>
</tr>
}
</table>
Page #(Model.PageCount < Model.PageNumber ? 0 : Model.PageNumber) of #Model.PageCount
<div id="myPager">
#Html.PagedListPager(Model, page => Url.Action("MasterDetail", new { page, OrderID = ViewBag.OrderID }))
</div>
<script type="text/javascript">
$(function () {
$.ajaxSetup({ cache: false });
setDialogLink($('a[btnName=btnCreate]'), 'Add New Asset', 500, 600, "contentFrame", "/Assets/MasterDetail");
setDialogLink($('a[btnName=btnEdit]'), 'Edit Customer', 500, 600, "contentFrame", "/Customers/Index");
setDialogLink($('a[btnName=btnDetails]'), 'Customer Details', 500, 600, "contentFrame", "/Customers/Index");
$('a[btnName=btnDelete]').click(function (e) {
e.preventDefault();
var confirmResult = confirm("Are you sure?");
if (confirmResult)
{
$('#contentFrame').mask("waiting ...");
$.ajax(
{
url: this.href,
type: 'POST',
data: JSON.stringify({}),
dataType: 'json',
traditional: true,
contentType: "application/json; charset=utf-8",
success:function(data)
{
if (data.success) {
$('#contentFrame').load("/Customers/Index");
}
else {
alert(data.errormessage);
}
$('#contentFrame').unmask("waiting ...");
},
error: function (data) {
alert("An error has occured!!!");
$('#contentFrame').unmask("waiting ...");
}
});
}
})
$("a[btnName=FilterCustomer]").click(function (e) {
e.preventDefault();
var search = $('input[name=search]').val();
this.href = this.href.replace('xyz', search);
$('#contentFrame').mask("waiting ...");
$.ajax({
url: this.href,
type: 'POST',
cache: false,
success: function (result) {
$('#contentFrame').unmask("waiting ...");
$('#contentFrame').html(result);
}
});
});
$(".SortButton").click(function (e) {
e.preventDefault();
$('#contentFrame').mask("waiting ...");
$.ajax({
url: this.href,
type: 'POST',
cache: false,
success: function (result) {
$('#contentFrame').unmask("waiting ...");
$('#contentFrame').html(result);
}
})
});
$('#myPager').on('click', 'a', function (e) {
e.preventDefault();
$('#contentFrame').mask("waiting ...");
$.ajax({
url: this.href,
type: 'GET',
cache: false,
success: function (result) {
$('#contentFrame').unmask("waiting ...");
$('#contentFrame').html(result);
}
});
});
});
</script>
My AssetsController Manage and MasterDetail methods which correlate to his HomeController Index and CustomerController Index methods respectively.
// GET: Assets
public ActionResult Manage()
{
return View();
}
// GET: MasterDetail
public ActionResult MasterDetail(int? page)
{
ApplicationUser user = System.Web.HttpContext.Current.GetOwinContext().GetUserManager<ApplicationUserManager>().FindById(User.Identity.GetUserId());
//ApplicationUser user = db.Users.First(u => u.Id == userr.Id);
var assets = db.Quantities.Where(a => a.VendorId == user.VendorId).OrderByDescending(a => a.AssetId);
int pageNumber = page ?? 1;
int pageSize = 3;
return PartialView(assets.ToPagedList(pageNumber, pageSize));
}
I am not too sure about what your problem is, but I THINK there I saw a problem in your code.
in MasterDetail.cshtml try replacing
#Html.PagedListPager(Model, page => Url.Action("_MasterDetail", new { page, OrderID = ViewBag.OrderID }))
with
#Html.PagedListPager(Model, page => Url.Action("MasterDetail", new { page, OrderID = ViewBag.OrderID }))
Url.Action expects an Action name, not a razor view name.
So last night while laying in bed stumped as to whats causing the problem I thought well maybe I should just look up alternatives. I saw some Ajax variations (that youll see commented out) and I ended up on this SO thread which ultimately lead me to a solution.
Below is the end result of my tinkering, I left commented code in from my attempts so you'll see other thigns I've tried. Other than this all I changed in the view was add a reference for a modal wait screen and then changed Html.ActionLink to a button. <input id="btnCustomers" type="button" value="Manage Assets" />
<script type="text/javascript">
$(function () {
$.ajaxSetup({cache : false})
$('#btnCustomers').click(function () {
//$('#contentFrame').mask("waiting ...");
waitingDialog.show("Please wait while we prepare your inventory ...");
$('#contentFrame').load('#Url.Action("MasterDetail","Assets")', function () {
setTimeout(function () {
waitingDialog.hide();
}, 1000);
});
//$.ajax({
// type: 'GET',
// url: '#Url.Content("~/Assets/MasterDetail")',
// data: -1,
// success: function (data) {
// $('#contentFrame').innerHtml = waitingDialog.hide();
//$('#contentFrame').load('#Url.Action("MasterDetail","Assets")');
// }
//})
//$('#contentFrame').load(this.href, function (response, status, xhr) {
// $('#contentFrame').unmask("waiting ...");
//});
return false;
});
});
</script>

Knockout Nested List Post Null

I'm trying integrate ko on one of my razor views. I've researched quite a bit yesterday but haven't been able to find a similar solution for my problem.
I have a record model:
public class Record
{
public Int Request Id {get;set;}
public string RecordName {get;set;}
public Person Person {get;set;}
public IList<Person> People { get; set; }
}
And a Person Model:
public class Person
{
public int Id { get; set; }
public string FirstName { get; set; }
public string LastName { get; set; }
public IList<Alias> Aliases { get; set; }
}
My View:
#model Record
#{
ViewBag.Title = "Index";
}
<h2>Index</h2>
#using (Html.BeginForm("PostRequest", "Request", FormMethod.Post))
{
#Html.LabelFor(m => m.Person.FirstName)
#Html.TextBoxFor(m => m.Person.FirstName)
<h5>People</h5>
<table>
<tbody data-bind="foreach: People">
<tr>
<td>#Html.LabelFor(m => m.Person.FirstName)</td>
<td><input type="text" data-bind="value: FirstName, attr: {name: 'People[' + $index() + '].FirstName'}" /></td>
<td>#Html.LabelFor(m => m.Person.LastName)</td>
<td><input type="text" data-bind="value: LastName, attr: {name: 'People[' + $index() + '].LastName'}" /></td>
</tr>
<tr>
<td><button id="removePerson" data-bind="click: $root.removePerson">Remove Person</button></td>
</tr>
<tr>
<td>
<button id="addAlias" data-bind="click: addAlias">Add Alias</button>
</td>
</tr>
<!-- ko foreach: Aliases -->
<tr>
<td>#Html.LabelFor(m => m.Alias.FirstNameAlias)</td>
<td><input type="text" data-bind="value: FirstNameAlias, attr: {name: 'Aliases[' + $index() + '].FirstNameAlias'}" /></td>
<td>#Html.LabelFor(m => m.Alias.LastNameAlias)</td>
<td><input type="text" data-bind="value: LastNameAlias, attr: {name: 'Aliases[' + $index() + '].LastNameAlias'}" /></td>
<td><button id="removeAlias" data-bind="click: $root.removeAlias">Remove Alias</button></td>
</tr>
<!-- /ko -->
</tbody>
</table>
<button id="addPerson" data-bind="click: addPerson">Add Person</button>
<button>Submit</button>
<input id="clickMe" type="button" value="clickme" onclick="submit();" />
}
And Script:
#section scripts
{
<script type="text/javascript">
$(function () {
var personItem = function () {
var self = this;
self.LastName = ko.observable();
self.FirstName = ko.observable();
self.Aliases = ko.observableArray();
};
var model = ko.mapping.fromJS(#Html.Raw(Model.ToJson()));
alert('The length of the array is ' + model.People().length);
alert('The first element is ' + model.People()[0].Aliases().length);
alert(ko.toJSON(model));
model.addPerson = function () {
model.People.push(new personItem());
};
model.removePerson = function (person) {
model.People.remove(person);
};
ko.applyBindings(model);
})
function submit() {
$.ajax({
url: '/Request/PostRequest',
type: 'POST',
contentType: 'application/json; charset=utf-8',
data: ko.toJSON(model),
success: function (status) {
alert(status);
}
});
};
</script>
}
The Controller action that GETs this view pre initializes some data for the record model, so the binding appears to be working properly, however when I post data, the data for Alias List comes back Null.
Controller:
public ActionResult CreateRequest(Record viewModel)
{
var list = new Record
{
People = new List<Person> {
new Person {FirstName = "My First Person", Aliases = new List<Alias> { new Alias{FirstNameAlias = "firstnamealias",LastNameAlias = "lastnamealias1"}},},
new Person {FirstName = "My Second Person", Aliases = new List<Alias> { new Alias{FirstNameAlias = "firstnamealias2", LastNameAlias ="lastnamealias2"}},}
},
Person = new Person()
{
FirstName = "me"
}
};
return View(list);
}
[HttpPost]
public JsonResult PostRequest(Record viewModel)
{
return Json(String.Format("'Success':'false','Error':'"));
}
I feel that I am missing something with ko.mapping. But so close, as the data populates from the GET controller action, but fails to POST.
SOLUTION
I updated my KO script, and the way I was rendering the ko data in the view. This has solved my problem.
Updated Script
<script>
var initialData = #Html.Raw(Serialize(Model.People));
var BackgroundModel = function(people) {
var self = this;
self.people = ko.mapping.fromJS(people);
self.addPerson = function() {
self.people.push({
FirstName: "",
LastName: "",
Aliases: ko.observableArray()
});
};
self.removePerson = function(person) {
self.people.remove(person);
};
self.addAlias = function(person) {
person.Aliases.push({
//todo
FirstNameAlias: "",
LastNameAlias: ""
});
};
self.removeAlias = function(Alias) {
$.each(self.people(), function() { this.Aliases.remove(Alias) })
};
self.save = function() {
self.lastSavedJson(JSON.stringify(ko.toJS(self.people), null, 2));
var subModel = JSON.stringify(ko.toJS(self));
$.ajax({
url: '/Request/PostRequest',
type: 'POST',
contentType: 'application/json; charset=utf-8',
data: subModel,
success: function (status) {
alert(status);
}
});
};
self.lastSavedJson = ko.observable("")
};
ko.applyBindings(new BackgroundModel(initialData));
</script>
Updated View
<div data-bind="foreach: people">
<div class="panel panel-default">
<div class="panel-heading">
<h4 class="panel-title"> <a data-bind="attr:{href:'#collapseOne'+$index()}, text:FirstName() +' '+ LastName()" #*href="#collapse_One"*# class="accordion-toggle" data-toggle="collapse" data-parent="#accordion"></a> </h4>
</div>
<div data-bind="attr:{id:'collapseOne'+$index()}" class="panel-collapse collapse in" #*data-bind="attr:{id:_collapseId, class:_collapsedIn}"*#>
<div class="panel-body">
<table>
<tbody>
<tr>
<td>#Html.DisplayNameFor(x => x.Person.FirstName)</td>
<td>#Html.DisplayNameFor(x => x.Person.LastName)</td>
</tr>
<tr>
<td><input data-bind="value: FirstName, name: FirstName" /></td>
<td><input data-bind="value: LastName, name: LastName" /></td>
</tr>
<tr>
<td><a href='#' data-bind='click: $root.removePerson'>Remove Person</a></td>
</tr>
</tbody>
</table>
<!-- ko foreach: Aliases -->
<table>
<tbody>
<tr>
<td>#Html.DisplayNameFor(x => x.Alias.FirstNameAlias)</td>
<td>#Html.DisplayNameFor(x => x.Alias.LastNameAlias)</td>
</tr>
<tr>
<td><input data-bind="value: FirstNameAlias, name: FirstNameAlias" /></td>
<td><input data-bind="value: LastNameAlias, name: LastNameAlias" /></td>
</tr>
<tr>
<td><a href='#' data-bind='click: $root.removeAlias'>Remove Alias</a></td>
</tr>
</tbody>
</table>
<!-- /ko -->
<a href='#' data-bind='click: $root.addAlias'>Add Alias</a>
</div>
</div>
</div>
</div>
The variable model in your submit funtion is going to be undefined it's not the model you're expecting it to be.
Move the submit method to in to your model...
$(function () {
var personItem = function () {
var self = this;
self.LastName = ko.observable();
self.FirstName = ko.observable();
self.Aliases = ko.observableArray();
};
var model = ko.mapping.fromJS(#Html.Raw(Model.ToJson()));
alert('The length of the array is ' + model.People().length);
alert('The first element is ' + model.People()[0].Aliases().length);
alert(ko.toJSON(model));
model.addPerson = function () {
model.People().push(new personItem());
};
model.removePerson = function (person) {
model.People().remove(person);
};
model.submit = function() {
$.ajax({
url: '/Request/PostRequest',
type: 'POST',
contentType: 'application/json; charset=utf-8',
data: ko.toJSON(model),
success: function (status) {
alert(status);
}
});
};
ko.applyBindings(model);
});
and update the binding on your button to
<input id="clickMe" type="button" value="clickme" data-bind="click: submit" />
Also
Controller.Json expects an object to serialize rather than a string
[HttpPost]
public JsonResult PostRequest(Record viewModel)
{
return Json(String.Format("'Success':'false','Error':'"));
}
Should be:
[HttpPost]
public JsonResult PostRequest(Record viewModel)
{
return Json(new { success = false, error: String.Empty });
}
Update
Also noticed another issue with updating the model.People array
model.addPerson = function () {
model.People.push(new personItem());
};
model.removePerson = function (person) {
model.People.remove(person);
};
In these functions model.People should be model.People(), i.e.
model.addPerson = function () {
model.People().push(new personItem());
};
model.removePerson = function (person) {
model.People().remove(person);
};
Notice the () after model.People - included in the code block above.

ASP.NET Mvc two dependent dropdownlist?

script
<script type="text/javascript">
$(document).ready(function () {
$('musteri_sno').change(function () {
$('form_sayac_secimi').submit(function () {
if ($(this).valid()) {
$.ajax({
url: this.action,
type: this.method,
data: $(this).serialize(),
success: function (result) {
}
});
}
return false;
});
});
});
</script>
html
#using (Html.BeginForm("SayacSecimiPartial", "SayacOkumalari", FormMethod.Post, new { id = "form_sayac_secimi" }))
{
<table>
<tr>
<td>
#Html.DropDownList("musteri_sno", (SelectList)ViewBag.musteri_id, "--Müşteri Seçiniz--", new { id = "musteri_sno" })
</td>
<td>
#Html.DropDownList("sayac_no", Enumerable.Empty<SelectListItem>(), "-- Sayaç Seçiniz --", new { id = "sayac_no" })
</td>
<td>
<input type="submit" value="Uygula" />
#Html.Hidden("sno", new { sno = ViewData["sno"] })
</td>
</tr>
</table>
}
I want to fill second dropdown with values that is returned from first one.How can I do this?
Thanks.
In the success callback of your ajax call, build the option tag filled with the values you are returned and then append it to the select tag named "sayac_no".
success: function(result) {
var opt = '';
for (var i = 0; i < result; i++) {
opt += '<option value="' + result[i].value + '">' + result[i].name + '</option>';
}
$('select[name=sayac_no]').html(opt);
}
I suppose the result object is a list of objects with two properties, name and value.
Modify it accordingly to your needs and improve it because this is just a very basic version.

Resources