not updating entity in viewmodel after post request using ajax - asp.net

I am new to knockout.js and i am using post method to update data into database . Here is my code
<%# Page Language="C#" AutoEventWireup="true" CodeFile="SProduct.aspx.cs" Inherits="SProduct" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<title></title>
<script src="Scripts/jquery-1.4.1.min.js" type="text/javascript"></script>
<script src="http://knockoutjs.com/downloads/knockout-2.2.1.js" type="text/javascript"></script>
</head>
<body>
<form id="form1" runat="server">
<div id="body">
<h2>
Knockout CRUD Operations with ASP.Net Form App</h2>
<h3>
List of Products</h3>
<table id="products1">
<thead>
<tr>
<th>
ID
</th>
<th>
Name
</th>
<th>
Category
</th>
<th>
Price
</th>
<th>
Actions
</th>
</tr>
</thead>
<tbody data-bind="foreach: Products">
<tr>
<td data-bind="text: Id">
</td>
<td data-bind="text: Name">
</td>
<td data-bind="text: Category">
</td>
<td data-bind="text: formatCurrency(Price)">
</td>
<td>
<button data-bind="click: $root.edit">
Edit</button>
<button data-bind="click: $root.delete">
Delete</button>
</td>
</tr>
</tbody>
<tfoot>
<tr>
<td>
</td>
<td>
</td>
<td>
Total :
</td>
<td data-bind="text: formatCurrency($root.Total())">
</td>
<td>
</td>
</tr>
</tfoot>
</table>
<br />
<div style="border-top: solid 2px #282828; width: 430px; height: 10px">
</div>
<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>
<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="category">
Category</label>
<input data-bind="value: $root.Category" type="text" title="Category" />
</div>
<div>
<label for="price">
Price</label>
<input data-bind="value: $root.Price" type="text" title="Price" />
</div>
<br />
<div>
<button data-bind="click: $root.create">
Save</button>
<button data-bind="click: $root.reset">
Reset</button>
</div>
</div>
</div>
<script type="text/javascript">
function formatCurrency(value) {
return "$" + value.toFixed(2);
}
function ProductViewModel() {
//Make the self as 'this' reference
var self = this;
//Declare observable which will be bind with UI
self.Id = ko.observable("");
self.Name = ko.observable("");
self.Price = ko.observable("");
self.Category = ko.observable("");
var Product = {
Id: self.Id,
Name: self.Name,
Price: self.Price,
Category: self.Category
};
self.Product = ko.observable();
self.Products = ko.observableArray(); // Contains the list of products
// Initialize the view-model
$.ajax({
url: 'SProduct.aspx/GetAllProducts',
cache: false,
type: 'POST',
contentType: 'application/json; charset=utf-8',
data: {},
success: function (data) {
// debugger;
$.each(data.d, function (index, prd) {
self.Products.push(prd);
})
//Put the response in ObservableArray
}
});
// Calculate Total of Price After Initialization
self.Total = ko.computed(function () {
var sum = 0;
var arr = self.Products();
for (var i = 0; i < arr.length; i++) {
sum += arr[i].Price;
}
return sum;
});
//Add New Item
self.create = function () {
Product.Id="333";
if (Product.Name() != "" && Product.Price() != "" && Product.Category() != "") {
$.ajax({
url: 'SProduct.aspx/Add',
cache: false,
type: 'POST',
contentType: 'application/json; charset=utf-8',
data:"{item:" + ko.toJSON(Product) + "}",
success: function (data) {
self.Products.push(data.d);
self.Name("");
self.Price("");
self.Category("");
},
error:function(data)
{
alert("error");
console.log(data.d);
}
});
}
else {
alert('Please Enter All the Values !!');
}
}
//Delete product details
self.delete = function (Product) {
if (confirm('Are you sure to Delete "' + Product.Name + '" product ??')) {
var id = Product.Id;
$.ajax({
url: 'SProduct.aspx/Delete',
cache: false,
type: 'POST',
contentType: 'application/json; charset=utf-8',
data:"{id:" + ko.toJSON(id) + "}",
success: function (data) {
self.Products.remove(Product);
},
error:function(data){
console.log(data.d);
alert('Error');
}
})
}
}
// Edit product details
self.edit = function (Product) {
self.Product(Product);
}
// Update product details
self.update = function () {
var Product = self.Product();
$.ajax({
url: 'SProduct.aspx/Update',
cache: false,
type: 'POST',
contentType: 'application/json; charset=utf-8',
data:"{Product:" + ko.toJSON(Product) + "}",
success: function (data) {
alert("success");
console.log(data.d);
// self.Products.removeAll();
// self.Products(data.d); //Put the response in ObservableArray
self.Product(null);
alert("Record Updated Successfully");
},
error: function (data) {
console.log(data);
}
})
}
// Reset product details
self.reset = function () {
self.Name("");
self.Price("");
self.Category("");
}
// Cancel product details
self.cancel = function () {
self.Product(null);
}
}
var viewModel = new ProductViewModel();
ko.applyBindings(viewModel);
</script>
</form>
</body>
</html>
Updated
Here is screen shot of my page . when i click on update ajax success function is called, but no change in above table field .

Why do you have to update the item back to the list? You're not doing anything to the properties of the object on the server side are you?
Your edit method should look something like this:
self.edit = function(item) {
self.Product(item);
};
and remove the following code nemesv said.
self.Products.removeAll();
self.Products(data.d); //Put the response in ObservableArray
My first post so be gentle ;)
Response to comment:
change your success to:
success: function (data) {
var product = ko.utils.arrayFirst(self.Products(), function(item) {
return (item.Id == data.d.Id);
}); // You could either update the product object with the new values from data.d or delete it and add a new product object.
for (var p in product ) {
product [p] = data.d[p];
}
self.Product(null);
alert("Record Updated Successfully");
},
Found a bug, it was replacing the observables with native values.
for (var p in product ) {
product [p](data.d[p]);
}
I took the liberty of simplifying the code and removing everything that hasn't anything to do with the update function. The following code example should work. ( I used knockout 2.3.0 and jQuery 1.9.1)
<script type="text/javascript">
function Product(id, name, price, category) {
var self = this;
self.Id = ko.observable(id);
self.Name = ko.observable(name);
self.Price = ko.observable(price);
self.Category = ko.observable(category);
}
function ProductViewModel() {
var self = this;
self.Product = ko.observable();
self.Products = ko.observableArray(); // Contains the list of products
$.ajax({
url: 'SProduct.aspx/GetAllProducts',
cache: false,
type: 'POST',
contentType: 'application/json; charset=utf-8',
data: {},
success: function (data) {
$.each(data.d, function (index, prd) {
var p = new Product(prd.Id, prd.Name, prd.Price, prd.Category);
self.Products.push(p);
});
}
});
self.Total = ko.computed(function () {
var sum = 0;
var arr = self.Products();
for (var i = 0; i < arr.length; i++) {
sum += arr[i].Price;
}
return sum;
});
self.edit = function(product) {
self.Product(product);
};
self.update = function() {
var product = self.Product();
$.ajax({
url: 'SProduct.aspx/Update',
cache: false,
type: 'POST',
contentType: 'application/json; charset=utf-8',
data: "{product:" + ko.toJSON(product) + "}",
success: function (data) {
for (var p in product) {
product[p](data.d[p]);
}
self.Product(null);
alert("Record Updated Successfully");
},
error: function(data) {
console.log(data);
}
});
};
self.reset = function() {
self.Name("");
self.Price("");
self.Category("");
};
self.cancel = function() {
self.Product(null);
};
}
$(document).ready(function() {
var viewModel = new ProductViewModel();
ko.applyBindings(viewModel);
});
</script>

Related

Blueimp File Upload: How to delete file? (MVC)

I'm attempting to tie Blueimp File Uploader into my MVC 5 solution. I have the uploads working as follows:
<span class="btn btn-success fileinput-button">
<i class="glyphicon glyphicon-plus"></i>
<span>Add files...</span>
<input id="fileupload" type="file" name="files[]" multiple>
</span>
<br />
<div class="progress">
<div class="progress-bar" role="progressbar" aria-valuenow="0" aria-valuemin="0" aria-valuemax="100" style="width: 0%;">
<span class="sr-only">0% complete</span>
</div>
</div>
<br />
<div class="file_name"></div>
<br />
<div class="file_type"></div>
<br />
<div class="file_size"></div>
<!-- The container for the uploaded files -->
<div id="files" class="files"></div>
and the javascript
$(document).ready(function () {
var Url = "#Url.Content("~/Advertise/UploadFiles")";
$('#fileupload').fileupload({
dataType: 'json',
url: Url,
autoUpload: true,
done: function (e, data) {
// $('.file_name').html(data.result.name);
// $('.file_type').html(data.result.type);
// $('.file_size').html(data.result.size);
}
}).on('fileuploadadd', function (e, data) {
data.context = $('<div/>').appendTo('#files');
$.each(data.files, function (index, file) {
var node = $('<p/>')
.append('<img src="' + URL.createObjectURL(data.files[0]) + '" height="50" width="50"/>').append($('<span/>').text(file.name));
if (!index) {
node
.append('<br>')
//.append(uploadButton.clone(true).data(data));
}
node.appendTo(data.context);
});
}).on('fileuploadprocessalways', function (e, data) {
var index = data.index,
file = data.files[index],
node = $(data.context.children()[index]);
if (file.preview) {
node
.prepend('<br>')
.prepend(file.preview);
}
if (file.error) {
node
.append('<br>')
.append($('<span class="text-danger"/>').text(file.error));
}
if (index + 1 === data.files.length) {
data.context.find('button')
.text('Upload')
.prop('disabled', !!data.files.error);
}
}).on('fileuploadprogressall', function (e, data) {
var progress = parseInt(data.loaded / data.total * 100, 10);
$('#progress .progress-bar').css(
'width',
progress + '%'
);
}).on('fileuploaddone', function (e, data) {
$.each(data.result.files, function (index, file) {
if (file.url) {
var link = $('<a>')
.attr('target', '_blank')
.prop('href', file.url);
$(data.context.children()[index])
.wrap(link);
} else if (file.error) {
var error = $('<span class="text-danger"/>').text(file.error);
$(data.context.children()[index])
.append('<br>')
.append(error);
}
});
}).on('fileuploadfail', function (e, data) {
$.each(data.files, function (index) {
var error = $('<span class="text-danger"/>').text('File upload failed.');
$(data.context.children()[index])
.append('<br>')
.append(error);
});
}).prop('disabled', !$.support.fileInput)
.parent().addClass($.support.fileInput ? undefined : 'disabled');
});
I've not tested a lot of the jQuery above. But I'm looking in to how I can delete an uploaded file? I could probably do it by calling a jQuery ajax post, but I think Blueimp has a native way to do it. But I can't find any documentation on it?? Any help appreciated.

KnockoutJS, get data from spring mvc controller and bind it to the view

im trying knockout doing a little test and i have not been able to do this very basic thing with knockout.. i want to return a list from my controller then take that list with my knockout viewmodel and finally bind it to a dropdown in my view.
i have this controller:
#RequestMapping(value="/getUsers", method = RequestMethod.GET)
public List<User> returnUsers(#ModelAttribute User user) {
User user1=new User(), user2, user3 ;
List<User>users=new ArrayList<User>();
user1.setLastName("adsfa");
user1.setName("adfds");
user1.setAge(26);
user2=new User();
user2.setLastName("testLastName2");
user2.setName("testName2");
user2.setAge(45);
user3=new User();
user3.setLastName("testLastName2");
user3.setName("testName3");
user3.setAge(33);
users.add(user1);
users.add(user2);
users.add(user3);
return users;
}
this is my knockout viewmodel:
function viewModel() {
this.name = ko.observable("bob");
this.lastName = ko.observable("smith");
this.age = ko.observable(26);
this.validationMessage = ko.observable();
this.users = ko.observableArray([]);
this.loadUsers(); //with this function call i want to initialize users with my controller data.
}
//this funcion should get the data from my controller
viewModel.prototype.loadUsers = function() {
var tmp = this.users();
$.get("/vacation_booking/getUsers", function (data) {
tmp(ko.toJS(data));
log.info("Usuarios:" + data);
});
}
/*
this.Age = ko.dependentObservable({
read: this.age,
write: function (value) {
if (!isNaN(value)) {
this.age(value);
this.validationMessage("");
}
else {
this.validationMessage("Age must be a number!");
}
},
owner: viewModel
});
*/
var save = function(){
// var jsonData = ko.toJSON(viewModel);
// alert("Could now send this to server: " + JSON.stringify(jsonData));
$.ajax({
url: "/vacation_booking/save",
dataType: "json",
type: "POST",
data: "name=" + this.name() + "&lastName=" + this.lastName() + "&age=" + this.age(),
success: function(data){
alert("Successful");
},
failure: function(){
alert("Unsuccessful");
}
});
}
ko.applyBindings(new viewModel());
this is my view:
<%# page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
</head>
<h1>Testing</h1>
<p>
<a href="${pageContext.request.contextPath}/specRunner" target=_blank>Launch Test Runner</a>
</p>
First Name: <input type="text" data-bind="
value: name,
valueUpdate : 'afterkeydown'
"/>
<br />
Last Name: <input type="text" data-bind="value:lastName, valueUpdate : 'afterkeydown'" />
<br />
Age: <input type="text" data-bind="value: age, valueUpdate : 'afterkeydown'" />
<Br />
<!--p>Destination country: <select data-bind=" options : availableCountries"></select></p-->
<Br />
<span data-bind="text: validationMessage" style="color:Red"></span>
<div>
<h2>Details:</h2>
<hr />
First Name: <span data-bind="text:name"></span> <br /><br />
Last Name: <span data-bind=" text:lastName"></span><br /><br />
Age: <span data-bind="text:age"></span><br />
<button data-bind="click:save">Submit</button>
<p>Usuarios: <select data-bind="options:users, value:name" type="text"></select></p>
</div>
<script src="resources/js/jquery-2.0.3.min.js" type="text/javascript"></script>
<script src="resources/js/knockout-3.0.0.js" type="text/javascript"></script>
<script type="text/javascript" src="resources/js/viewModel.js"> </script>
</body>
</html>
don't use this.users() and use prototype for save method also.
viewModel.prototype.loadUsers = function() {
var tmp = this.users;
$.get("/vacation_booking/getUsers", function (data) {
tmp(ko.toJS(data));
log.info("Usuarios:" + data);
});
}
viewModel.prototype.save = function(){
// var jsonData = ko.toJSON(viewModel);
// alert("Could now send this to server: " + JSON.stringify(jsonData));
$.ajax({
url: "/vacation_booking/save",
dataType: "json",
type: "POST",
data: "name=" + this.name() + "&lastName=" + this.lastName() + "&age=" + this.age(),
success: function(data){
alert("Successful");
},
failure: function(){
alert("Unsuccessful");
}
});
}
second thing you can return json data directly from controller.
check this sample at fiddle

Knockout observables not binding and applyBindings firing twice

I had earlier asked this question here which worked in a html file. Now I am trying to put the same in the ASP.NET webform but does not seem to work.
What happens here the first time the page loads ajax call fires which I do not want except when the cursor is moved away from the text box
On Blur I have a popup window that I want to show the data returned from the ajax call. The data does not bind either. What am I doing wrong here.
My Javascript:
<script type="text/javascript">
var self = this;
function showPopUp() {
var cvr = document.getElementById("cover")
var dlg = document.getElementById("dialog")
var SName = document.getElementById("<%=txtSurname.ClientID%>").value
document.getElementById("txtSurnameSearch").value = SName
cvr.style.display = "block"
dlg.style.display = "block"
if (document.body.style.overflow = "hidden") {
cvr.style.width = "1024"
cvr.style.height = "100;"
}
this.SurnameViewModel(SName) //<= here I pass the surname to the ViewModel
}
function closePopUp(el) {
var cvr = document.getElementById("cover")
var dlg = document.getElementById(el)
cvr.style.display = "none"
dlg.style.display = "none"
document.body.style.overflowY = "scroll"
}
function SurnameViewModel(Surname) {
var self = this;
self.Surnames = ko.observableArray();
$.ajax({
crossDomain: true,
type: 'POST',
url: "http://localhost/GetSurnames/Name/ChurchID",
dataType: 'json',
data: { "Name":Surname, "ChurchID": "17" },
processdata: true,
success: function (result) {
alert(result.data);
ko.mapping.fromJSON(result.data, {}, self.Surnames);
},
error: function (xhr, ajaxOptions, thrownError) {
alert("Failure!");
alert(xhr.status);
alert(thrownError);
}
});
}
$(document).ready(function () {
ko.applyBindings(new SurnameViewModel());
});
</script>
My HTML
<!-- Grey Background -->
<div id="cover"></div>
<!-- Surname Popup -->
<div id="dialog" style="display:none">
My Dialog Content
<br /><input ID="txtSurnameSearch" type="text" />
<br /><input type="button" value="Submit" />
<br />[Close]
<pre data-bind="text: ko.toJSON($data, null, 2)"></pre> //<= just shows the header
<table>
<thead>
<tr>
<th>ID</th>
<th>Family Name</th>
<th></th>
</tr>
</thead>
<tbody data-bind="foreach: Surnames">
<tr>
<td data-bind="value: id"></td>
<td data-bind="value: homename"></td>
</tr>
</tbody>
</table>
</div>
TextBox where the onBlur is called:
<asp:TextBox ID="txtSurname" MaxLength="50" runat="server" Width="127px" class="txtboxes" placeholder="Last Name" onblur="showPopUp();" />
JSON Data returned by the ajax call
{"data":"[{\"id\":3,\"homename\":\"D\\u0027Costa\"}]"}
Edit 1:
If I hard code the values in the ajax call it seems to bind but still fires on page load
data: { "Name":"d", "ChurchID": "17" },
In your view model your Ajax call is inline, not inside a method, so as an instance of its contstructed your AJAX gets fired off. See this code, we create a global variable to hold the instance of your model and then wrap the AJAX call into its on function (method) in your JS. Then you can just call the method on your instance when you need to in your popup code.
var self = this;
var model = new SurnameViewModel();
function showPopUp() {
var cvr = document.getElementById("cover")
var dlg = document.getElementById("dialog")
var SName = document.getElementById("<%=txtSurname.ClientID%>").value
document.getElementById("txtSurnameSearch").value = SName
cvr.style.display = "block"
dlg.style.display = "block"
if (document.body.style.overflow = "hidden") {
cvr.style.width = "1024"
cvr.style.height = "100;"
}
model.GetSurname(SName) //<= here I pass the surname to the ViewModel
}
function closePopUp(el) {
var cvr = document.getElementById("cover")
var dlg = document.getElementById(el)
cvr.style.display = "none"
dlg.style.display = "none"
document.body.style.overflowY = "scroll"
}
function SurnameViewModel() {
var self = this;
self.Surnames = ko.observableArray();
self.GetSurname = function(Surname){
$.ajax({
crossDomain: true,
type: 'POST',
url: "http://localhost/GetSurnames/Name/ChurchID",
dataType: 'json',
data: { "Name":Surname, "ChurchID": "17" },
processdata: true,
success: function (result) {
alert(result.data);
ko.mapping.fromJSON(result.data, {}, self.Surnames);
},
error: function (xhr, ajaxOptions, thrownError) {
alert("Failure!");
alert(xhr.status);
alert(thrownError);
}
});
}
}
$(document).ready(function () {
ko.applyBindings(model);
});
</script>

KnockoutJs mapping JSON to viewmodel

I'm having problem with binding JSON from ASP.net webform webapi to the viewmodel with KnockoutJs. There is no problem with wepapi and mapping to mappedQuickEntries.
Where did I get it wrong? Thanks.
Error:
Error: Unable to parse bindings.
Message: ReferenceError: ItemPartNumb is not defined;
Bindings value: value: ItemPartNumb
View:
<div>
<table border="1" cellpadding="0" cellspacing="0">
<tbody data-bind="foreach: quickEntries">
<tr>
<td data-bind="value: ItemPartNumb"></td>
<td data-bind="value: ItemDescription"></td>
</tr>
</tbody>
</table>
ViewModel:
<script type="text/javascript">
var QuickEntry = function(_itemPartNumb, _itemDescription) {
this.ItemPartNumber = ko.observable(_itemPartNumb);
this.ItemDescription = ko.observable(_itemDescription);
};
function QuickEntriesViewModel () {
var self = this;
self.quickEntries = ko.observableArray([]);
$.ajax({
url: '/DesktopModules/Blah/API/Data/GetTenQuickEntries',
type: 'GET',
dataType: 'json',
success: function (data) {
var mappedQuickEntries = $.map(data, function (item) {
return new QuickEntry(item.ItemPartNumb, item.ItemDescription);
});
self.quickEntries(mappedQuickEntries);
},
statusCode: {
404: function () {
alert('Failed');
}
}
});
};
ko.applyBindings(new QuickEntriesViewModel());
ItemPartNumb vs ItemPartNumber
And you are using the value-binding instead of the text-binding.
http://jsfiddle.net/MizardX/9sqvk/

Partial view render on button click

I have Index view:
#using System.Web.Mvc.Html
#model MsmqTestApp.Models.MsmqData
<!DOCTYPE html>
<html>
<head>
<script src="#Url.Content("~/Scripts/jquery.unobtrusive-ajax.min.js")" type="text/javascript"></script>
<meta name="viewport" content="width=device-width" />
<title>MsmqTest</title>
</head>
<body>
<div>
<input type="submit" id="btnBuy" value="Buy" onclick="location.href='#Url.Action("BuyItem", "MsmqTest", new { area = "Msmq" })'" />
<input type="submit" id="btnSell" value="Sell" onclick="location.href='#Url.Action("SellItem", "MsmqTest", new { area = "Msmq" })'" />
</div>
<div id="msmqpartial">
#{Html.RenderPartial("Partial1", Model); }
</div>
</body>
</html>
and partial:
#using System.Web.Mvc.Html
#model MsmqTestApp.Models.MsmqData
<p>
Items to buy
#foreach (var item in Model.ItemsToBuy)
{
<tr>
<td>#Html.DisplayFor(model => item)
</td>
</tr>
}
</p>
<p>
<a>Items Selled</a>
#foreach (var item in Model.ItemsSelled)
{
<tr>
<td>#Html.DisplayFor(model => item)
</td>
</tr>
}
</p>
And controller:
public class MsmqTestController : Controller
{
public MsmqData data = new MsmqData();
public ActionResult Index()
{
return View(data);
}
public ActionResult BuyItem()
{
PushIntoQueue();
ViewBag.DataBuyCount = data.ItemsToBuy.Count;
return PartialView("Partial1",data);
}
}
How to do that when i Click one of button just partial view render, now controller wants to move me to BuyItem view ;/
The first thing to do is to reference jQuery. Right now you have referenced only jquery.unobtrusive-ajax.min.js but this script has dependency on jQuery, so don't forget to include as well before it:
<script src="#Url.Content("~/Scripts/jquery.jquery-1.5.1.min.js")" type="text/javascript"></script>
<script src="#Url.Content("~/Scripts/jquery.unobtrusive-ajax.min.js")" type="text/javascript"></script>
Now to your question: you should use submit buttons with an HTML form. In your example you don't have a form so it would be semantically more correct to use a normal button:
<input type="button" value="Buy" data-url="#Url.Action("BuyItem", "MsmqTest", new { area = "Msmq" })" />
<input type="button" value="Sell" data-url="#Url.Action("SellItem", "MsmqTest", new { area = "Msmq" })" />
and then in a separate javascript file AJAXify those buttons by subscribing to the .click() event:
$(function() {
$(':button').click(function() {
$.ajax({
url: $(this).data('url'),
type: 'GET',
cache: false,
success: function(result) {
$('#msmqpartial').html(result);
}
});
return false;
});
});
or if you want to rely on the Microsoft unobtrusive framework you could use AJAX actionlinks:
#Ajax.ActionLink("Buy", "BuyItem", "MsmqTest", new { area = "Msmq" }, new AjaxOptions { UpdateTargetId = "msmqpartial" })
#Ajax.ActionLink("Sell", "SellItem", "MsmqTest", new { area = "Msmq" }, new AjaxOptions { UpdateTargetId = "msmqpartial" })
and if you want buttons instead of anchors you could use AJAX forms:
#using (Ajax.BeginForm("BuyItem", "MsmqTest", new { area = "Msmq" }, new AjaxOptions { UpdateTargetId = "msmqpartial" }))
{
<button type="submit">Buy</button>
}
#using (Ajax.BeginForm("SellItem", "MsmqTest", new { area = "Msmq" }, new AjaxOptions { UpdateTargetId = "msmqpartial" }))
{
<button type="submit">Sell</button>
}
From what I can see you have already included the jquery.unobtrusive-ajax.min.js script to your page and this should work.
Maybe not the solution you were looking for but, I would forget about partials and use Javascript to call the server to get the data required and then return the data to the client as JSON and use it to render the results to the page asynchronously.
The JavaScript function;
var MyName = (function () {
//PRIVATE FUNCTIONS
var renderHtml = function(data){
$.map(data, function (item) {
$("<td>" + item.whateveritisyoureturn + "</td>").appendTo("#msmqpartial");
});
};
//PUBLIC FUNCTIONS
var getData = function(val){
// call the server method to get some results.
$.ajax({ type: "POST",
url: "/mycontroller/myjsonaction",
dataType: "json",
data: { prop: val },
success: function (data) {
renderHtml();
},
error: function () {
},
complete: function () {
}
});
};
//EXPOSED PROPERTIES AND FUNCTIONS
return {
GetData : getData
};
})();
And on the Server....
public JsonResult myjsonaction(string prop)
{
var JsonResult;
// do whatever you need to do
return Json(JsonResult);
}
hope this helps....

Resources