Backbone View Events Firing for Each Instance of a View - events

A have a parent view OpenOrderListView that creates instances of OpenOrderViews that have events on them. The result I'm trying to gain is when the markCompleted button of an OpenOrderView is clicked a function be called to tell the model to set that attribute.
The functionality is working but it is being called on all OpenOrderViews inside the parent (OpenOrderListView) instead of just the view in which the click event was handled. How can I make this event only trigger on the view that was acted upon?
Code is below
window.OpenOrderListView = Backbone.View.extend({
el: 'table.openOrders tbody',
initialize: function() {
_.bindAll(this,'render');
this.render();
},
render : function() {
var $openOrders
var models = this.collection.open();
for (var i = models.length - 1; i >= 0; i--) {
console.log('model', models[i]);
console.log("this.template", this.template);
new OpenOrderView({'model': models[i], 'el': this.el});
};
}
});
window.OpenOrderView = Backbone.View.extend({
initialize: function() {
console.log('this', this);
_.bindAll(this,'render',
'markCompleted',
'markInProgress');
this.render();
},
events : {
"click .markCompleted": "markCompleted",
"click .markInProgress": "markInProgress",
},
markCompleted: function(){
console.log(this);
this.model.markCompleted();
},
markInProgress: function(){
console.log("markInProgress",this);
this.model.markInProgress();
console.log('markInProgress Complete');
},
template : 'template-openOrderView',
render : function() {
console.log("View Rendered");
$(this.el).append(tmpl(this.template, this.model.toJSON()));
}
window.Order = Backbone.Model.extend({
url: function(){
return "/api/order/id/"+this.get("id");
},
isCompleted: function(){
return this.get('status') == "completed";
},
isInProgress: function(){
return this.get('status') == "inProgress";
},
isOpen: function(){
return this.get('status') == "open";
},
markCompleted: function(){
this.set({'status':"completed"});
console.log('markCompleted');
return this.save();
},
markInProgress: function(){
this.set({'status':"inProgress"});
console.log('markInProgress');
return this.save();
},
markOpen: function(){
this.set({'status':"open"});
console.log('markOpen');
return this.save();
}
});
})
OrderView Template
<tr class="order">
<td class="preview hide_mobile">
<img src="{%=o.thumbnail_url%}">
</td>
<td class="name">
{%=o.name%}
</td>
<td class="description"><span>{%=o.description%}</span></td>
<td class="hide_mobile date_added"><span>{%=o.date_added%}</span></td>
<td class="hide_mobile user"><span>{%=o.username%}</span></td>
<td class="status">
<a class="btn modal-download" target="_blank" href="{%=o.url%}" title="{%=o.name%}" download="{%=o.name%}">
<i class="icon-download"></i>
<span>Download</span>
</a>
<button class="markCancel btn btn-danger" data-type="{%=o.delete_type%}" data-url="{%=o.delete_url%}">
<i class="icon-remove icon-white"></i>
<span>Cancel</span>
</button>
<button class="markInProgress btn btn-primary" data-type="" data-url="">
<i class="icon-repeat icon-white"></i>
<span>Mark In Progress</span>
</button>
<button class="markCompleted btn btn-success" data-type="" data-url="">
<i class="icon-ok icon-white"></i>
<span>Mark Completed</span>
</button>
</td>

All the SubViews are sharing the same DOM element table.openOrders tbody. This is done in the line new OpenOrderView({'model': models[i], 'el': this.el});.
So when you declare events like this:
events : {
"click .markCompleted": "markCompleted"
}
What is happening is that all DOM elements that match this table.openOrders tbody .markCompleted will be binded with this click event.
You need each SubView to have each own this.el DOM element.
In your case I think is better if your SubViews create theirs own DOM element in the air like this:
// code simplified an not tested
window.OpenOrderView = Backbone.View.extend({
tagName: 'tr',
attributes: { class: "order" },
initialize: function(){
// don't render() here
},
// ... rest of your code
render: function(){
this.$el.html(tmpl(this.template, this.model.toJSON()));
return this;
}
})
Look that now the SubView is not rendering itself, neither appending its DOM element directly to the page, it will be a job for the ParentView:
// code simplified an not tested
window.OpenOrderListView = Backbone.View.extend({
render : function() {
var $openOrders
var models = this.collection.open();
for (var i = models.length - 1; i >= 0; i--) {
var openOrderView = new OpenOrderView({'model': models[i]});
this.$el.append( openOrderView.render().el );
};
});
I think this is a very common pattern.
PD: You have to modify your template removing the tr open/close.

Related

Dynamically Binding the the Oracle jet switcher slot to the oracle jet add and remove tab(Make switcher slot dynamic in oracle jet)

I want to make tab switcher auto decide the slot for the switcher but when I am trying to make it dynamic with the help of observable no data is showing the tab content area until I write the slot area statically. With observable variable, the slot is not getting the selected Slot value.
Please check how I can do this.
slot = [[selectedSlot]] //using for the slot value in html
this.selectedSlot = ko.observable('settings');
<div id="tabbardemo">
<oj-dialog class="tab-dialog hidden" id="tabDialog" dialog-title="Tab data">
<div slot="body">
<oj-form-layout>
<oj-input-text id="t1" value="{{newTabTitle}}" label-hint="Title"></oj-input-text>
</oj-form-layout>
</div>
<div slot="footer">
<oj-button id="idOK" on-oj-action="[[addTab]]">OK</oj-button>
<oj-button id="idCancel" on-oj-action="[[closeDialog]]">Cancel</oj-button>
</div>
</oj-dialog>
<oj-button id="addTab" on-oj-action="[[openDialog]]">Add Tab</oj-button>
<br/>
<br/>
<oj-tab-bar contextmenu="tabmenu" id="hnavlist" selection="{{selectedItem}}" current-item="{{currentItem}}" edge="top" data="[[dataProvider]]"
on-oj-remove="[[onRemove]]">
<template slot="itemTemplate" data-oj-as="item">
<li class="oj-removable" :class="[[{'oj-disabled' : item.data.disabled}]]">
<a href="#">
<oj-bind-text value="[[item.data.name]]"></oj-bind-text>
</a>
</li>
</template>
<oj-menu slot="contextMenu" class="hidden" aria-label="Actions">
<oj-option data-oj-command="oj-tabbar-remove">
Removable
</oj-option>
</oj-menu>
</oj-tab-bar>
<oj-switcher value="[[selectedItem]]">
<div slot="[[selectedSlot]]"
id="home-tab-panel"
role="tabpanel"
aria-labelledby="home-tab">
<div class="demo-tab-content-style">
<h2>Home page content area</h2>
</div>
</div>
<div slot="tools"
id="tools-tab-panel"
role="tabpanel"
aria-labelledby="tools-tab">
<div class="demo-tab-content-style">
<h1>Tools Area</h1>
</div>
</div>
<div slot="base"
id="base-tab-panel"
role="tabpanel"
aria-labelledby="ba`enter code here`se-tab">
<div class="demo-tab-content-style">
<h1>Base Tab</h1>
</div>
</div>
</oj-switcher>
<br>
<div>
<p class="bold">Last selected list item:
<span id="results">
<oj-bind-text value="[[selectedItem]]"></oj-bind-text>
</span>
</p>
</div>
</div>
JS code below
require(['ojs/ojcontext',
'knockout',
'ojs/ojbootstrap',
'ojs/ojarraydataprovider',
'ojs/ojknockout',
'ojs/ojnavigationlist',
'ojs/ojconveyorbelt',
'ojs/ojdialog',
'ojs/ojbutton',
'ojs/ojinputtext',
'ojs/ojformlayout',
'ojs/ojswitcher',
],
function (Context, ko, Bootstrap, ArrayDataProvider) { // this callback gets executed when all required modules are loaded
function ViewModel() {
this.data = ko.observableArray([{
name: 'Settings',
id: 'settings'
},
{
name: 'Tools',
id: 'tools'
},
{
name: 'Base',
id: 'base'
}
]);
this.selectedSlot = ko.observable('settings'); //Sepecifically mentioned to show what it is the objective
this.dataProvider = new ArrayDataProvider(this.data, { keyAttributes: 'id' });
this.selectedItem = ko.observable('settings');
this.currentItem = ko.observable();
this.tabCount = 0;
this.newTabTitle = ko.observable();
this.delete = (function (id) {
var hnavlist = document.getElementById('hnavlist');
var items = this.data();
for (var i = 0; i < items.length; i++) {
if (items[i].id === id) {
this.data.splice(i, 1);
Context.getContext(hnavlist)
.getBusyContext()
.whenReady()
.then(function () {
hnavlist.focus();
});
break;
}
}
}).bind(this);
this.onRemove = (function (event) {
this.delete(event.detail.key);
event.preventDefault();
event.stopPropagation();
}).bind(this);
this.openDialog = (function () {
this.tabCount += 1;
this.newTabTitle('Tab ' + this.tabCount);
document.getElementById('tabDialog').open();
}).bind(this);
this.closeDialog = function () {
document.getElementById('tabDialog').close();
};
this.addTab = (function () {
var title = this.newTabTitle();
var tabid = 'tid' + this.tabCount;
this.data.push({
name: title,
id: tabid
});
this.closeDialog();
}).bind(this);
}
Bootstrap.whenDocumentReady().then(function () {
ko.applyBindings(new ViewModel(), document.getElementById('tabbardemo'));
});
}
);
It is a bit complex to understand when you copy from JET cookbook. You have done almost everything right. Just make the following changes:
1) Remove this:
Bootstrap.whenDocumentReady().then(function () {
ko.applyBindings(new ViewModel(), document.getElementById('tabbardemo'));
});
Why? The bootstrapping is required once per application, which is done inside your main.js file.
2) Replace require by define
Why? Require block is again maintained in main.js, where your required modules are pre-loaded. All subsequent viewModels have define block
3) Return an instance of your ViewModel
define([
... Your imports
],
function (Context, ko, Bootstrap, ArrayDataProvider) { // this callback gets executed when all required modules are loaded
function ViewModel() {
// Your code
}
return ViewModel;
});

Asp.Net Mvc Html.BeginFormSubmit ajax sends twice request (one's type xhr the other's document)

I am working on a survey application with Asp.Net MVC. I have a page named Index.cshtml which has a question table and a 'Add New' button.Once button clicked, a popup is opened with jQuery. I am calling a view from controller to fill jQuery dialog named as AddOrEdit.cshtml (child page). I am adding new question and options. Question is a textfield and its options are added in editable table. Once clicked submt button Submit form event (save or update) is fired. But ajax sends twice request. One of these requests send empty object, the other sends full object. Where am I making a mistake?
According to my research, what causes this problem is that the unobtrusive validator is placed on 2 different pages. But this is not the case for me.
When I debug with chrome in f12, the initiator of one of the 2 requests 'jquery' the initiator of the other 'other' The type of one of these 2 post requests appears as 'XHR' and the type of the other is 'document'.
Index.cshtml
#{
ViewBag.Title = "Soru Listesi";
}
<h2>Soru Oluşturma</h2>
<a class="btn btn-success" style="margin-bottom: 10px"
onclick="PopupForm('#Url.Action("AddOrEdit","Question")')"><i class="fa fa-plus"></i> Yeni Soru Oluştur</a><table id="questionTable" class="table table-striped table-bordered accent-blue" style="width: 100%">
<thead>
<tr>
<th>Soru No</th>
<th>Soru Adı</th>
<th>Oluşturma Tarihi</th>
<th>Güncelleme Tarihi</th>
<th>Güncelle/Sil</th>
</tr>
</thead>
</table>
<link
href="https://cdn.datatables.net/1.10.20/css/dataTables.bootstrap4.min.css" rel="stylesheet" />
<link href="https://stackpath.bootstrapcdn.com/font-awesome/4.7.0/css/font-awesome.min.css"
rel="stylesheet" />
#section Scripts{
<script src="https://cdn.datatables.net/1.10.20/js/jquery.dataTables.min.js"></script>
<script src="https://cdn.datatables.net/1.10.20/js/dataTables.bootstrap4.min.js"></script>
<script>
var Popup, dataTable;
$(document).ready(function() {
dataTable = $("#questionTable").DataTable({
"ajax": {
"url": "/Question/GetData",
"type": "GET",
"datatype": "json"
},
"columnDefs": [
{ targets: 2 }
],
"scrollX": true,
"scrollY": "auto",
"columns": [
{ "data": "QuestionId" },
{ "data": "QuestionName" },
{
"data": "CreatedDate",
"render": function(data) { return getDateString(data); }
},
{
"data": "UpdatedDate",
"render": function(data) { return getDateString(data); }
},
{
"data": "QuestionId",
"render": function(data) {
return "<a class='btn btn-primary btn-sm' onclick=PopupForm('#Url.Action("AddOrEdit", "Question")/" +
data +
"')><i class='fa fa-pencil'></i> Güncelle</a><a class='btn btn-danger btn-sm' style='margin-left:5px' onclick=Delete(" +
data +
")><i class='fa fa-trash'></i> Sil</a>";
},
"orderable": false,
"searchable": false,
"width": "150px"
}
],
"language": {
"emptyTable":
"Soru bulunamadı, lütfen <b>Yeni Soru Oluştur</b> butonuna tıklayarak yeni soru oluşturunuz. "
}
});
});
function getDateString(date) {
var dateObj = new Date(parseInt(date.substr(6)));
let year = dateObj.getFullYear();
let month = (1 + dateObj.getMonth()).toString().padStart(2, '0');
let day = dateObj.getDate().toString().padStart(2, '0');
return day + '/' + month + '/' + year;
};
function PopupForm(url) {
var formDiv = $('<div/>');
$.get(url)
.done(function(response) {
formDiv.html(response);
Popup = formDiv.dialog({
autoOpen: true,
resizable: true,
title: 'Soru Detay',
modal: true,
height: 'auto',
width: '700',
close: function() {
Popup.dialog('destroy').remove();
}
});
});
}
function SubmitForm(form) {
debugger;
if (form.checkValidity() === false) {
debugger;
event.preventDefault();
event.stopPropagation();
}
form.classList.add('was-validated');
if ($(form).valid()) {
var question = {};
question.questionId = 1111;
var options = new Array();
$("#questionForm TBODY TR").each(function() {
var row = $(this);
var option = {};
option.OptionId = row.find("TD").eq(0).html();
option.OptionName = row.find("TD").eq(1).html();
options.push(option);
});
question.options = options;
question.responses = new Array();
$.ajax({
type: "POST",
url: form.action,
data: JSON.stringify(question),
success: function(data) {
if (data.success) {
debugger;
Popup.dialog('close');
dataTable.ajax.reload();
$.notify(data.message,
{
globalPosition: "top center",
className: "success",
showAnimation: "slideDown",
gap: 1000
});
}
},
error: function(req, err) {
debugger;
alert('req : ' + req + ' err : ' + err.data);
},
complete: function(data) {
alert('complete : ' + data.status);
}
});
}
}
function ResetForm(form) {
Popup.dialog('close');
return false;
}
function Delete(id) {
if (confirm('Bu soruyu silmek istediğinizden emin misiniz?')) {
$.ajax({
type: "POST",
url: '#Url.Action("Delete", "Question")/' + id,
success: function(data) {
if (data.success) {
dataTable.ajax.reload();
$.notify(data.message,
{
className: "success",
globalPosition: "top center",
title: "BAŞARILI"
})
}
}
});
}
}
</script>
}
AddOrEdit.cshtml
#using MerinosSurvey.Models
#model Questions
#{
Layout = null;
}
#using (Html.BeginForm("AddOrEdit", "Question", FormMethod.Post, new { #class = "needs-validation",
novalidate = "true", onsubmit = "return SubmitForm(this)", onreset = "return ResetForm(this)", id =
"questionForm" }))
{
<div class="form-group row">
#Html.Label("QuestionId", "Soru No", new { #class = "col-form-label col-md-3" })
<div class="col-md-9">
#Html.TextBoxFor(model => model.QuestionId, new { #readonly = "readonly", #class = "form-control" })
</div>
</div>
<div class="form-group row">
#Html.Label("QuestionName", "Soru Adı", new { #class = "col-form-label col-md-3" })
<div class="col-md-9">
#Html.EditorFor(model => model.QuestionName, new { htmlAttributes = new { #class = "form-control", required = "true" } })
<div class="valid-feedback"><i class="fa fa-check">Süpersin</i></div>
<div class="invalid-feedback "><i class="fa fa-times"></i></div>
</div>
</div>
#*<div class="form-group row">
#Html.LabelFor(model => model.CreatedDate, new { #class = "form-control-label col-md-3"})
<div class="col-md-9">
#Html.EditorFor(model => model.CreatedDate, "{0:yyyy-MM-dd}", new { htmlAttributes = new { #class = "form-control", type = "date", #readonly = "readonly",required="false" } })
</div>
</div>*#
<div class="table-wrapper form-group table-responsive-md">
<div class="table-title">
<div class="form-group row">
<div class="col-md-9">Seçenekler</div>
<div class="col-md-3">
<a class="btn btn-success add-new" style="margin-bottom: 10px"><i class="fa fa-plus"></i>Seçenek Ekle</a>
</div>
</div>
</div>
<table class="table optionTable">
<thead>
<tr>
<th scope="col">Seçenek Id</th>
<th scope="col">Seçenek Adı</th>
<th scope="col">Güncelle/Sil</th>
</tr>
</thead>
<tbody>
#*#foreach (Options options in Model.Options)
{
<tr>
<td>#options.OptionId</td>
<td>#options.OptionName</td>
<td>
<a class="add btn btn-primary btn-sm" title="Add" data-toggle="tooltip">
<i class="fa fa-check">Onayla</i></a>
<a class="edit btn btn-secondary btn-sm" title="Edit" data-toggle="tooltip"><i class="fa fa-pencil">Güncelle</i></a>
<a class="delete btn-danger btn-sm" title="Delete" data-toggle="tooltip"><i class="fa fa-trash">Sil</i></a>
</td>
</tr>
}*#
</tbody>
</table>
</div>
<div class="form-group row">
<input type="submit" value="Submit" class="btn btn-primary" id="btnSubmit" />
<input type="reset" value="Reset" class="btn btn-secondary" />
</div>
}
<script>
$(document).ready(function () {
$('[data-toggle="tooltip"]').tooltip();
//var actions = $("table.optionTable td:last-child").html();
var actions =' <a class="add btn btn-primary btn-sm" title="Add" data-toggle="tooltip"><i
class="fa fa-check">Onayla</i></a>' + '<a class="edit btn btn-secondary btn-sm" title="Edit" data toggle="tooltip"><i class="fa fa-pencil">Güncelle</i></a>' +'<a class="delete btn-danger btn-sm" title="Delete" data-toggle="tooltip"><i class="fa fa-trash">Sil</i></a>';
// Append table with add row form on add new button click
$(".add-new").click(function () {
$(this).attr("disabled", "disabled");
var index = $("table.optionTable tbody tr:last-child").index();
var row = '<tr>' +
'<td><input type="text" class="form-control" name="optionId" id="optionId"></td>' +
'<td><input type="text" class="form-control" name="optionId" id="optionName"></td>' +
'<td>' + actions + '</td>' +
'</tr>';
$("table.optionTable").append(row);
$("table.optionTable tbody tr").eq(index + 1).find(".add, .edit").toggle();
$('[data-toggle="tooltip"]').tooltip();
});
// Add row on add button click
$(document).on("click", ".add", function () {
var empty = false;
var input = $(this).parents("tr").find('input[type="text"]');
input.each(function () {
if (!$(this).val()) {
$(this).addClass("error");
empty = true;
} else {
$(this).removeClass("error");
}
});
$(this).parents("tr").find(".error").first().focus();
if (!empty) {
input.each(function () {
$(this).parent("td").html($(this).val());
});
$(this).parents("tr").find(".add, .edit").toggle();
$(".add-new").removeAttr("disabled");
}
});
// Edit row on edit button click
$(document).on("click", ".edit", function () {
$(this).parents("tr").find("td:not(:last-child)").each(function () {
$(this).html('<input type="text" class="form-control" value="' + $(this).text() + '">');
});
$(this).parents("tr").find(".add, .edit").toggle();
$(".add-new").attr("disabled", "disabled");
});
// Delete row on delete button click
$(document).on("click", ".delete", function () {
debugger;
$(this).parents("tr").remove();
$(".add-new").removeAttr("disabled");
});
});
event.preventDefault(); move this line and place it immediately after function SubmitForm (form){
Like below:
function SubmitForm(form) {
debugger;
event.preventDefault();
if (form.checkValidity() === false) {
debugger;
event.stopPropagation();
}
form.classList.add('was-validated');
if ($(form).valid()) {
var question = {};
question.questionId = 1111;
var options = new Array();
$("#questionForm TBODY TR").each(function() {
var row = $(this);
var option = {};
option.OptionId = row.find("TD").eq(0).html();
option.OptionName = row.find("TD").eq(1).html();
options.push(option);
});
question.options = options;
question.responses = new Array();
$.ajax({
type: "POST",
url: form.action,
data: JSON.stringify(question),
success: function(data) {
if (data.success) {
debugger;
Popup.dialog('close');
dataTable.ajax.reload();
$.notify(data.message,
{
globalPosition: "top center",
className: "success",
showAnimation: "slideDown",
gap: 1000
});
}
},
error: function(req, err) {
debugger;
alert('req : ' + req + ' err : ' + err.data);
},
complete: function(data) {
alert('complete : ' + data.status);
}
});
}
}

Load content into bootstrap popover using angular and ajax don't work

I am trying to populate a content into an bootstrap popover using angular and ajax. Although the data have been loaded correctly (as i can see in console.log) the result don't appear in the popover's content. I think the angular's loading is not ready yet when the bootstrap popover is loaded. Thus, how can i populate this popover immediately after angular load?
This is the code:
$(function() {
var p = $("#popover").popover({
content: $("#popover-content").html(),
html: true
});
});
(function () {
var app = angular.module("ng-app", []);
app.controller("NotificationsController", function ($scope, $http) {
$scope.links = [];
$scope.load = function () {
$http.get("json.php").success(function (response) {
console.log(response);
$scope.links = response;
// the response return is somethin like
// [
// {title: "Google", url: "http://www.google.com"},
// {title: "Gmail", url: "http://www.google.com"},
// ]
});
};
$scope.load();
});
})();
<ul class="nav navbar-nav">
<li data-ng-controller="NotificationsController as notification">
<a href="#" data-toggle="popover" id="popover" title="Notificações" data-placement="bottom" data-trigger="focus">
<span class="badge">{{links.length}}</span>
</a>
<div id="popover-content" style="display: none">
<div data-ng-repeat="link in links">
{{link.title}}
</div>
</div>
</li>
</ul>
Thanks in advance
You can put your function inner the controller, to get angular cycle. And, also, define your jquery call on a $timeout event.
Please look this sample on jsbin: jsbin
controller('c', function($scope, $timeout) {
$scope.getData = function() {
return $("#popover-content").html();
};
$timeout(function() {
$("#popover").popover({
content: $scope.getData,
html: true
});
});
}

Knockout - load data into model with Ajax - not straight away

Here's a simplified example of my knockout model. The problem I'm having is that as soon as the page loads, the quiz is loaded. Why does it get run straight away and how can I stop it so that it only get's run when I want, say, on the click of a button?
Do I even need to use subscribe to do this?
HTML:
<h1>Test</h1>
<button class="btn btn-primary" data-bind="click: quizCount(quizCount() + 1)">
Click Me
</button>
<hr />
<div data-bind="visible: !loaded()">No Quiz</div>
<div data-bind="visible: loaded">Quiz Loaded!</div>
<hr />
<h3>Debug</h3>
<div data-bind="text: ko.toJSON(quizModel)"></div>
Javascript:
<script type="text/javascript">
var quizModel = { };
// DOM ready.
$(function () {
function QuizViewModel() {
var self = this;
self.loaded = ko.observable(false);
self.questions = ko.observable();
self.quizCount = ko.observable();
};
quizModel = new QuizViewModel();
quizModel.quizCount.subscribe(function (newCount) {
$.getJSON('#Url.Action("GetNew", "api/quiz")', function (data) {
quizModel.questions(data.Questions);
}).complete(function () {
quizModel.loaded(true);
});
});
ko.applyBindings(quizModel);
})
</script>
Subscribe is only used for listening to changes in an observable so it will run immediately as soon as the observable gets a value.
You need to add this function to your viewmodel as a method, likely to be called getQuestions:
function QuizViewModel() {
var self = this;
self.loaded = ko.observable(false);
self.questions = ko.observable();
self.quizCount = ko.observable();
self.getQuestions = function(){
$.getJSON('#Url.Action("GetNew", "api/quiz")', function (data) {
self.questions(data.Questions);
}).complete(function () {
self.loaded(true);
});
}
};
then you can easily have a button or something that binds to this method on click:
<button data-bind="click: getQuestions">Get questions</button>

MVC3 reloading part of page with data razor

I have a table with my data from base and 3 buttons to delete, create and update which return PartialViews.
I want to update the part of my page with data after clicking the submit button in the corresponding dialog (delete, update, ...).
What is the easiest way to achive this?
This is what I've got now
I will just add, delete is mostly the same.
<div id="delete-dialog" title="Delete Product"></div>
<script type="text/javascript" >
$(".deleteLink").button();
var deleteLinkObj;
// delete Link
$('.deleteLink').click(function () {
deleteLinkObj = $(this);
var name = $(this).parent().parent().find('td :first').html();
$('#delete-dialog').html('<p>Do you want delete ' + name + ' ?</p>');
//for future use
$('#delete-dialog').dialog('open');
return false; // prevents the default behaviour
});
$('#delete-dialog').dialog({
dialogClass: "ConfirmBox",
autoOpen: false, width: 400, resizable: false, modal: true, //Dialog options
buttons: {
"Continue": function () {
$.post(deleteLinkObj[0].href, function (data) { //Post to action
if (data == '<%= Boolean.TrueString %>') {
deleteLinkObj.closest("tr").hide('fast'); //Hide Row
}
else {
}
});
$(this).dialog("close");
},
"Cancel": function () {
$(this).dialog("close");
}
}
});
</script>
And after dialog close I want something like a reload of a part of the page.
The data looks like
<table>
<tr>
<th> Name </th>
<th> Date </th>
<th> </th>
</tr>
#foreach (var m in this.Model)
{
<tr>
<td>
<div class="ProductName">#Html.DisplayFor(Model => m.Name)</div>
</td>
<td>
#Convert.ToDateTime(m.AddDate).ToShortDateString()
</td>
<td>
<div class="ProductPrice">#string.Format("{0:C}", m.Price)</div>
</td>
<td>
<div class="CategoryName">#Html.DisplayFor(Model => m.CategoryName)</div>
</td>
<td>
#Html.ActionLink("Edit", "Edit", new { id = m.ID }, new { #class = "editLink" })
#Html.ActionLink("Delete", "Delete", new { id = m.ID }, new { #class = "deleteLink" })
</td>
</tr>
}
</table>
I'm not sure if im doing this well
I tried to put this action after click the button but nut sure if is right
I changed the Index to a Partial View
buttons: {
"Continue": function () {
$.post(deleteLinkObj[0].href, function (data) { //Post to action
if (data == '<%= Boolean.TrueString %>') {
deleteLinkObj.closest("tr").hide('fast'); //Hide Row
}
else {
}
});
$.ajax.ActionLink("Index",
"Index", // <-- ActionMethod
"Shop", // <-- Controller Name.
new { }, // <-- Route arguments.
null // <-- htmlArguments .. which are none. Y
)
$(this).dialog("close");
},
"Cancel": function () {
$(this).dialog("close");
}
}
I suggest you use the ASP.NET MVC ActionLink helper in your .cshtml file, and not jQuery:
[...]
<script type="text/JavaScript">
function openPopup()
{
// Set your options as needed.
$("#yourPopupDialogId").dialog("open");
}
</script>
[...]
#Ajax.ActionLink(
"Delete",
"Delete",
"Controller",
new { someValue = 123 },
new AjaxOptions
{
// Set your options as needed
HttpMethod = "GET",
UpdateTargetId = "yourPopupDialogId",
OnSuccess = "openPopup()"
}
)
[...]
<div id="yourPopupDialogId" style="display: none;"></div>
Now in your Controller for the methods you want to use for your popups you should return PartialViews:
public ActionResult Delete(int id)
{
RecordDeleteModel model = YourRepository.GetModel( id );
return PartialView( model );
}

Resources