Display Data on Dialogbox without reloading page - javascript

am trying to display bootstrap dialog box with ID + Name + Price on it.
Then if user choose YES on the dialog, it must hit the Action method where there’s delete function and refresh the data on the page to see the change without reloading the page.
Also I don’t want after it hits the Delete user action method, it must not display its View.
I tried to use ViewBag from the below code but it doesn’t show me the ID + Name + Price on the Bootstrap Dialogbox, and doesn’t redirect to delete action method, and doesn’t refresh the page
#model IEnumerable<School.Models.ApplicationUser>
<hr>
<table class="table table-responsive table-hover">
<tbody>
#foreach (var item in Model.OrderBy(x => x.DateTime))
{
<tr>
<td>
#Html.DisplayFor(modelItem => item.ID)
</td>
<td>
#Html.DisplayFor(modelItem => item.Name)
</td>
<td>
#Html.DisplayFor(modelItem => item.Price)
</td>
<td>
<span style="color: #ff0000;">
<a class="btn btn-warning btn-sm disclaimer-dialog">
<i class="fa fa-unlock"> </i>Delete
ViewBag.MyId = #item.Id;
</a>
</span>
</td>
#ViewBag.MyId
</tr>
}
</tbody>
</table>
#section Scripts {
#Scripts.Render("~/bundles/jqueryval")
#Scripts.Render("~/Scripts/Views/SchoolAccounts/Delete.js")
}
<!-- Button trigger modal -->
<!-- Modal -->
<div class="modal fade" id="disclaimerModalDialog" tabindex="-1" role="dialog" aria-labelledby="exampleModalScrollableTitle" aria-hidden="true" data-keyboard="false" data-backdrop="static">
<div class="modal-dialog modal-dialog-scrollable" role="document">
<div class="modal-content">
<div class="modal-header">
<h3 class="modal-title" id="exampleModalScrollableTitle">Confirmation Deletion</h3>
<button type="button" class="close" data-dismiss="modal" aria-label="Close"></button>
</div>
<div class="modal-body">
<p><strong>Are you sure you want to reset password for user ? #ViewBag.MyId </strong></p>
#using (Html.BeginForm("DeleteProduct", "SchoolAccounts",
FormMethod.Post, new
{
#id = "delete-form",
role = "form"
}))
{
#*#Html.HiddenFor(m => m.Id)
#Html.AntiForgeryToken()*#
}
</div>
<div class="modal-footer">
<button type="button" class="btn btn-default"
onclick="$('#delete-form').submit();">
Yes
</button>
<button type="button" class="btn btn-primary"
data-dismiss="modal">
No
</button>
</div>
</div>
</div>
</div>
Content of Delete.js
$(function () {
$('.disclaimer-dialog').click(function () {
$('#disclaimerModalDialog').modal('show');
});
});

ViewBag can't be used like that. Once ViewBag is rendered on a page, you can't update its value. All razor variables are static once the page has finished loading.
What we need to do is assign those values on the html attributes.
Modify the link in your loop to have data-properties. I used data-id, data-name, data-price;
#foreach (var item in Model.OrderBy(x => x.DateTime))
{
<tr>
#*just modify the link in the last column*#
<td>
<span style="color: #ff0000;">
<a data-id="#item.Id" data-name="#item.Name" data-price="#item.Price" class="btn btn-warning btn-sm disclaimer-dialog">
<i class="fa fa-unlock"> </i>
Delete
</a>
</span>
</td>
</tr>
}
Modify your Delete.js to access those attributes and replace the content of the modal.
$(function () {
$('.disclaimer-dialog').click(function () {
// get attributes from the button
var id = $(this).data("id");
var name = $(this).data("name");
var price = $(this).data("price");
// Assign value to delete-id
$(".delete-id").val(id);
// update the first paragraph in modal-body
$('#disclaimerModalDialog').find(".modal-body p").eq(0).html("Are you sure you want to delete "+id+"-"+name+"-"+price+"?");
$('#disclaimerModalDialog').modal('show');
});
});
In your modal body, use this for the input field. We need to add a class so we can easily access it;
#Html.HiddenFor(m => m.Id, new { #class="delete-id" });
Add this function to your Delete.js
$(function(){
$("#delete-form").submit(function(e){
// this will stop the page from refreshing or redirecting
e.PreventDefault();
var deleteId = $(".delete-id").val();
var passData = { id:deleteId };
// ajax call here
$.ajax({
type: "POST",
url: "/ControllerName/DeleteAjax",
data: JSON.stringify(passData),
contentType: "application/json; charset=utf-8",
dataType: "html",
success: function(result){
alert(result);
// find the link with data-id == deleteid
// .parent() = span
// .parent().parent() = td
// .parent().parent().parent() = tr
// .remove() = remove that row
$("table a[data-id='"+deleteId+"']").parent().parent().parent().remove();
},
error: function(err){
alert(err);
}
});
});
});
In your controller, add this function. DeleteAjax;
[HttpPost]
public ActionResult DeleteAjax(string id)
{
var product = context.Products.FirstOrDefault(p=>p.Id == id);
if(product == null){
return Content("error, cant find Id")
}else{
context.Products.Remove(product);
context.SaveChanges();
return Content("successfully deleted");
}
}

Related

Getting a 405 error when trying to call Delete Modal Confirmation action (Asp.Net Core 6 javascript)

I'm working on my first Asp.Net Core application, and am struggling with modals, Razor pages and route mapping are completely new things for me, and javascript is a pretty old thing for me. I'm trying to create a delete modal that can be used for any object (my test object is of type Employee). Maybe this isn't possible, I'm not sure. My modal displays fine, but when I click to call my DeletePOST method I get a 405 error. The URL in question returns as https://localhost:44313/Employee/DeletePOST/1 (when the employee with id = 1 is selected). The "warning" message that I get in the console is
(index):6789 crbug/1173575, non-JS module files deprecated.(anonymous) # (index):6789.
Here is the applicable code from View.Employee.Index
<tbody>
#foreach (var employee in Model)
{
<tr id="row_#employee.Id">
<td>#employee.Name</td>
<td>#employee.Phone</td>
<td>#employee.Email</td>
<td>#employee.Address</td>
<td>#employee.Role</td>
<td>#employee.Availability</td>
<td class="w-100 btn-group" role="group">
<a asp-controller="Employee" asp-action="Edit" asp-route-id="#employee.Id"
class="btn btn-primary mx-2"> <i class="bi bi-pencil-square"></i> Edit</a>
<!--delete modal confirmation button-->
<a class="btn btn-danger delete" id="#delete" data-id="#employee.Id"
data-url ="#Url.Action("DeletePOST","Employee")/"
data-body-message= "Are you sure you want to delete this employee?">
<i class="bi bi-trash"></i> Delete</a>
</td>
</tr>
}
</tbody>
Code from wwwroot.js.delete.js
$((function () {
var target;
var pathToDelete;
var id;
$('body').append(`
<div class="modal fade" id="deleteModal" tabindex="-1" role="dialog"
aria-labelledby="myModalLabel">
<div class="modal-dialog" role="document">
<div class="modal-content">
<div class="modal-header">
<button type="button" class="close" data-bs-dismiss="modal"
aria-label="Close"><span aria-hidden="true">×</span> </button>
<h4 class="modal-title" id="myModalLabel">Warning</h4>
</div>
<div class="modal-body delete-modal-body">
</div>
<div class="modal-footer">
<button type="button" class="btn btn-default" data-dismiss="modal"
id="cancel-delete">Cancel</button>
<button type="submit" class="btn btn-danger"
id="confirm-delete">Delete</button>
</div>
</div>
</div>
</div>`);
//Delete Action
$(".delete").on('click', (e) => {
e.preventDefault();
target = e.target;
id = $(target).data('id');
pathToDelete = $(target).data('url');
var bodyMessage = $(target).data('body-message');
pathToDelete = pathToDelete + id;
$(".delete-modal-body").text(bodyMessage);
$("#deleteModal").modal('show');
});
$("#confirm-delete").on('click', () => {
window.location.href = pathToDelete; //suspect issue
});
}()));
Code from Controllers.EmployeeController.cs
[HttpPost]
[ValidateAntiForgeryToken]
public IActionResult DeletePOST(int? id)
{
var selectedEmployee = _db.Employees.Find(id);
if (selectedEmployee == null)
{
return NotFound();
}
_db.Employees.Remove(selectedEmployee);
_db.SaveChanges();
return RedirectToAction("Index"); //suspect issue
}
```
If you want to call DeletePOST in js,you can try to use ajax,since you need to add AntiForgeryToken to the request,you also need to add #Html.AntiForgoryTokento your view:
view:
<tbody>
#foreach (var employee in Model)
{
<tr id="row_#employee.Id">
<td>#employee.Name</td>
<td>#employee.Phone</td>
<td>#employee.Email</td>
<td>#employee.Address</td>
<td>#employee.Role</td>
<td>#employee.Availability</td>
<td class="w-100 btn-group" role="group">
<a asp-controller="Employee" asp-action="Edit" asp-route-id="#employee.Id"
class="btn btn-primary mx-2"> <i class="bi bi-pencil-square"></i> Edit</a>
<!--delete modal confirmation button-->
<a class="btn btn-danger delete" id="#delete" data-id="#employee.Id"
data-url ="#Url.Action("DeletePOST","Employee")/"
data-body-message= "Are you sure you want to delete this employee?">
<i class="bi bi-trash"></i> Delete</a>
</td>
</tr>
}
</tbody>
#Html.AntiForgoryToken
js:
$("#confirm-delete").on('click', () => {
$.ajax({
type: "POST",
url: pathToDelete,
headers: { "RequestVerificationToken": $('input[name="__RequestVerificationToken"]').val() },
}).done(function (result) {
//redirect to Index here
window.location.href="Index";
});
});
Or you can remove the following code in Controller:
[HttpPost]
[ValidateAntiForgeryToken]

Modal doesn't come with input's values

I have to use modals in my project. But unfortunately it does not work well.
On the page, when I click on the Add New Role button, everything goes right. But then when I click on the role edit button, the modal is displayed with blank values. While the IDs are successfully sent to the action.
After that when you reload the page, and first click on the edit role button, the modal will not display at all. At the same time, if you click the Add New Role button again, the modal is successfully displayed and everything is OK. At the same time, if you click the role edit button again, the modal will be displayed again in blank. (Just as before the IDs were successfully sent to the action but not found). I think this problem is related to two things:
The problem is with the action (maybe the code I wrote didn't send
the values well)
The problem may be that the following JQuery codes is not
performing well:
Jquery (file name: application-role-index.js):
(function ($) {
function RoleList() {
var $this = this;
function initilizeModel() {
$("#modal-action-application-role").on('loaded.bs.modal', function (e) {
}).on('hidden.bs.modal', function (e) {
$(this).removeData('bs.modal');
});
}
$this.init = function () {
initilizeModel();
}
}
$(function () {
var self = new RoleList();
self.init();
})
}(jQuery))
Anyway i hope you can help me. Here is the code I will use for this section:
Action in 'RoleListController':
[HttpGet]
public async Task<IActionResult> AddEditRole(string Id)
{
RoleListViewModel model = new RoleListViewModel();
if (!string.IsNullOrEmpty(Id))
{
ApplicationRole applicationRole = await _roleManager.FindByIdAsync(Id);
if (applicationRole != null)
{
model.Id = applicationRole.Id;
model.Name = applicationRole.Name;
model.Explanation = applicationRole.Explanation;
}
return PartialView("_AddAndEditAppRole", model);
}
else
{
return PartialView("_AddAndEditAppRole");
}
}
The View page i'm using modal:
<div class="btn-group">
<a class="btn btn-primary" id="showaddrole" data-toggle="modal" asp-action="AddEditRole" data-target="#modal-action-application-role">افزودن نقش جدید</a>
</div>
<table dir="rtl" class="table table-bordered table-striped myTable table-condensed">
<thead>
<tr>
<th>ID</th>
<th>#Html.DisplayNameFor(Model => Model.Name)</th>
<th>#Html.DisplayNameFor(Model => Model.Explanation)</th>
<th>#Html.DisplayNameFor(Model => Model.NumberOfUsers)</th>
<th>عملیات</th>
</tr>
</thead>
<tbody>
#foreach (var role in Model)
{
<tr>
<td>#role.Id</td>
<td>#role.Name</td>
<td>#role.Explanation</td>
<td>#role.NumberOfUsers</td>
<td>
<a class="btn btn-info myTableIC" asp-route-id="#role.Id" asp-action="AddEditRole" data-target="#modal-action-application-role" data-toggle="modal">
<i class="glyphicon glyphicon-pencil"></i>
</a>
<a class="btn btn-danger myTableIC" asp-route-id="#role.Id" asp-action="DeleteRole">
<i class="glyphicon glyphicon glyphicon-remove"></i>
</a>
</td>
</tr>
}
</tbody>
</table>
#Html.Partial("_Modal", new BootstrapModel { ID = "modal-action-application-role", Size = ModalSize.Medium })
#section Scripts{
<script src="~/js/modal-js/application-role-index.js"></script>
}
I have prepared a short video of how my program works so you can move forward with a better understanding:
You can find that by this link...
i suggest a solution at first create a div block with a unique id
<div id="popup"></div>
than use ajax to call the action like this :
$("#btnAdd").click(function () {
$.ajax({
type: 'POST',
url: '#Url.Action("AddEditRole")',
success: function (result) {
$("#popup").html(result);
$("#popup-addRole").modal("show");
}
});
});
then create an partiel view of popup with the id of model is popup-addRole something like this
<div class="modal" id="popup-edt" role="dialog">
<div class="modal-dialog" role="document" style="width:50%;">
<div class="modal-content">
<div class="modal-header">
<button type="button" class="close" data-dismiss="modal" aria-label="Close"><span aria-hidden="true">×</span></button>
</div>
<div class="modal-body">
//add your form here
</div>
</div>
</div>
</div>
don't forget to add model you want to use
i hope that fix the problem

Dynamic content for model popup based on link selected

I have an array of Accept Reject button. if a user clicks on these buttons separate model popup will show. Accept and reject button link has separate data-id and data-action.
My aim to write a single javascript function to load the content of the model popup instead of repeating the code of modal.
ERB code
<% #non_claim_items.each do |damage_item| %>
<tr>
<td>
<div class="input-prepend">
<span class="add-on"><%= damage_item.estimated_total_repair_cost.currency %></span>
<span class="uneditable-input input-small currency-format"><%= damage_item.estimated_total_repair_cost %></span>
</div>
</td>
<td>
<a data-toggle="modal" data-target="#acceptModel" data-id="<%= damage_item.id %>" data-action = 'accept' class="btn btn-small btn-primary">Accept</a>
<a data-toggle="modal" data-target="#rejectModel" data-id="<%= damage_item.id %>" data-action = 'discuss' class="btn btn-small btn-default">Discuss</a>
</td>
</tr>
<% end %>
<div id="acceptModel" class="modal fade hide" role="dialog">
<div class="modal-dialog">
<!-- Modal content-->
<div class="modal-content">
<div class="modal-header">
<button type="button" class="close" data-dismiss="modal">×</button>
<h4><%= t('headings.damage_item.accept_damage') %></h4>
</div>
<div class="modal-body" style="max-height: 500px;">
</div>
<div class="modal-footer">
<button type="button" class="btn btn-primary" ><%= t('navigation.buttons.confirm') %></button>
<button type="button" class="btn btn-default" data-dismiss="modal"><%= t('navigation.buttons.cancel') %></button>
</div>
</div>
</div>
Against each item have one accept/discuss button, data_id and data action are data parameter to model pop.
Script
<script type="text/javascript">
var damage_items = '<%= #non_claim_items.only(:id, :estimated_total_repair_cost, :damage_location_name ).to_json.html_safe %>';
$('a[data-toggle=modal]').click(function () {
if (typeof $(this).data('id') !== 'undefined') {
data_id = $(this).data('id');
action = $(this).data('action');
setModelContent($(this), action, data_id)
}
});
function setModelContent(modal, action, data_id) {
if( action == 'accept')
{
// based on action need to set the body of model pop up
}
}
</script>
I need help to write a javascript function that can set the body of model popup as per action.
Based on data_id, need to pick the corresponding data from the damage_items javascript variable, then data stored in the jquery hash need to show in the model popup body.
You can do it like this:
function setModelContent(modal, action, data_id) {
if (action == 'accept') {
// based on action need to set the body of model pop up
}
// Get damage item by data_id
let damage_item = Object.entries(damage_items).filter(item => item[1].id == data_id);
// Creating dynamically bootstrap elements and setting value of inputs by damage_item
let fisrtLabel = $(document.createElement('label')).text('Cost:');
let fistInput = $(document.createElement('input')).addClass('form-control').val(damage_item[0][1].estimated_total_repair_cost);
let firstCol6 = $(document.createElement('div')).addClass('col-sm-6')
.append(fisrtLabel)
.append(fistInput);
let secondLabel = $(document.createElement('label')).text('location name:');
let secondInput = $(document.createElement('input')).addClass('form-control').val(damage_item[0][1].damage_location_name);
let secondCol6 = $(document.createElement('div')).addClass('col-sm-6')
.append(secondLabel)
.append(secondInput);
let formGroup = $(document.createElement('div'))
.addClass('form-group')
.append(firstCol6)
.append(secondCol6);
// Clearing modal-body and filling it by new elements
$('#acceptModel').find('.modal-body').html("").append(formGroup);
}
Online demo (jsFiddle)

How to create bootstrap 4 confirmation modal for delete in ASP.NET MVC

I'm having trouble creating bootstrap confirmation modal in ASP.NET MVC. I've managed to successfully call modal when clicking on delete link inside view, but when I want to confirm, nothing happens.
Index View()
<p>
#Html.ActionLink("Create New", "Create")
</p>
<table class="table">
<tr>
<th>
#Html.DisplayNameFor(model => model.CurrentGrade.GradeName)
</th>
<th>
#Html.DisplayNameFor(model => model.Name)
</th>
<th>
#Html.DisplayNameFor(model => model.Surname)
</th>
<th></th>
</tr>
#foreach (var item in Model) {
<tr>
<td>
#Html.DisplayFor(modelItem => item.CurrentGrade.GradeName)
</td>
<td>
#Html.DisplayFor(modelItem => item.Name)
</td>
<td>
#Html.DisplayFor(modelItem => item.Surname)
</td>
<td>
#Html.ActionLink("Edit", "Edit", new { id=item.StudentId }) |
#Html.ActionLink("Details", "Details", new { id=item.StudentId }) |
#Html.ActionLink("Delete", "Delete", new { id=item.StudentId }, new { #class="element", #data_toggle = "modal", #data_target = "#exampleModalCenter" })
</td>
</tr>
}
</table>
Here is modal that I'm calling:
<div class="modal fade" id="exampleModalCenter" tabindex="-1" role="dialog" aria-labelledby="exampleModalLabel" aria-hidden="true">
<div class="modal-dialog" role="document">
<div class="modal-content">
<div class="modal-header">
<h5 class="modal-title" id="exampleModalLabel">Modal title</h5>
<button type="button" class="close" data-dismiss="modal" aria-label="Close">
<span aria-hidden="true">×</span>
</button>
</div>
<div class="modal-body">
<h6>Are you sure that you want to delete this?</h6>
</div>
<div class="modal-footer">
<button type="button" class="btn btn-secondary" data-dismiss="modal">Close</button>
<button type="button" class="btn btn-danger">Delete</button>
</div>
</div>
</div>
</div>
And finally, here is my simple js script.
$(document).ready(function () {
$('.element').click(function (e) {
$('#exampleModalCenter').modal('show');
if (confirm) {
return true;
} else {
return false;
}
});
});
UPDATE
I tried edit js code according to link that Soham provided but without any luck.
$(document).ready(function () {
$('#exampleModalCenter').on('show.bs.modal', function (e) {
$(this).find('.btn-danger').attr('href', $(e.relatedTarget).data('href'));
$('.debug-url').html('Delete URL: <strong>' + $(this).find('.btn-danger').attr('href') + '</strong>');
});
});
Maybe problem lies in #Html.ActionLink for Delete?
#Html.ActionLink("Delete", "Delete", new { id = item.StudentId }, new { #data_toggle = "modal", #data_target = "#exampleModalCenter" })
I was able to reproduce your issue and found some things required to get confirm modal popup work.
Assumed Delete action method exists:
[HttpPost]
public ActionResult Delete(int id)
{
// other stuff
return View();
}
Here are those key points:
1) Add data-id attribute to ActionLink method.
#Html.ActionLink("Delete", "Delete", new { id=item.StudentId }, new { #class="element",
#data_toggle = "modal", #data_target = "#exampleModalCenter",
#data_id = item.StudentId })
2) Add a hidden field which stores value of StudentId to delete.
#Html.Hidden("itemid", "", new { id = "itemid" })
3) Add id element to 'Delete' button in modal popup.
<div class="modal-footer">
<button type="button" class="btn btn-secondary" data-dismiss="modal">Close</button>
<button type="button" id="Delete" class="btn btn-danger">Delete</button>
</div>
4) Use this script inside document.ready to show modal popup and make request for 'Delete' button click:
$('.element').click(function (e) {
e.preventDefault();
$('#exampleModalCenter').modal('show');
var id = $(this).data('id');
$('#itemid').val(id);
});
$('#Delete').click(function () {
var studentId = $('#itemid').val();
$.post(#Url.Action("Delete", "Delete"), { id: studentId }, function (data) {
// do something after calling delete action method
// this alert box just an example
alert("Deleted StudentId: " + studentId);
});
$('#exampleModalCenter').modal('hide');
});
Live example: .NET Fiddle
Similar issues:
MVC Actionlink & Bootstrap Modal Submit
bootstrap modal for delete confirmation mvc
If you already have the delete action setup in the controller by entity framework, when you added a controller with actions, it should not be complicated, as all what you have to do after the user confirms the delete is to redirect to the delete action view by using simple JavaScript code and a hidden field to hold the item id to pass it in with the URL string.
The bootstrap dialog modal
<!-- Confirmation modal -->
<div class="modal fade" id="confirmdelete" tabindex="-1" role="dialog" aria-labelledby="confirmdelete" aria-hidden="true">
<div class="modal-dialog modal-dialog-centered" role="document">
<div class="modal-content">
<div class="modal-header">
<h5 class="modal-title" id="confirmdelete">Action Confirmation</h5>
<button type="button" class="close" data-dismiss="modal" aria-label="Close">
<span aria-hidden="true">×</span>
</button>
</div>
<div class="modal-body">
<p>Are you sure you want to delete this record ??</p>
</div>
<div class="modal-footer">
<button type="button" class="btn btn-secondary" data-dismiss="modal">Cancel</button>
<button type="button" class="btn btn-primary" id="action">Delete</button>
</div>
</div>
</div>
</div>
Hidden field to hold the item id to be deleted
Make sure it is placed inside the foreach loop
#Html.HiddenFor(c => item.ID, new { #id = "hdnItemId" })
Jquery simple code to redirect to the delete action with item id included
$(document).ready(function () {
$('#action').click(function () {
var itemId = $('#hdnItemId').val();
var actionLink = "/Banks/Delete/" + itemId;
window.location.href = actionLink;
});
});
The above answer is correct and easy but jquery code is supposed to be like this:
$(document).ready(function () {
$('#action').click(function () {
var itemId = $('#hdnItemId').val();
var actionLink = "/MyController/MyDeleteAction?id=" + itemId;
window.location.href = actionLink;
});
});

MVC - Html.Action to retrieve element using Javascript, then pass it as parameter to Controller, then return a PartialView

View - My view has a modal that has an #Html.Action that calls the PartialViewResult in Controller. Notice the #Html.Action("RetrieveItemPrice", new { item_Id = 1 }) still has predefined item_Id.
Q#1: How do I create a function that will get an element's value and put it in the item_Id parameter before sending it to the Controller? Could this be inserted in the #Html.Action?
<div id="myModal" class="modal fade" role="dialog">
<div class="modal-dialog">
<!-- Modal content-->
<div class="modal-content">
<div class="modal-header">
<button type="button" class="close" data-dismiss="modal">×</button>
<h4 class="modal-title">Modal Header</h4>
</div>
<div class="modal-body">
<div id="pvPrice" class="" style="border: 0px solid green; ">
#Html.Action("RetrieveItemPrice", new { item_Id = 1 })
</div>
</div>
<div class="modal-footer">
<button type="button" class="btn btn-default" data-dismiss="modal">Close</button>
</div>
</div>
</div>
</div>
<table id="dbTable">
<thead>
<tr>
<th class="hidden">
#Html.DisplayNameFor(model => model.itemId)
</th>
<th>
#Html.DisplayNameFor(model => model.itemName)
</th>
</tr>
</thead>
<tbody id="dbBody">
#foreach (var item in Model.Items)
{
<tr>
<td class="hidden">
#Html.DisplayFor(modelItem => item.itemid)
</td>
<td>
#Html.DisplayFor(modelItem => item.itemname)
</td>
</tr>
}
</tbody>
</table>
Controller
public PartialViewResult RetrieveItemPrice(string item_Id)
{
var prices = from ip in _odb.ITEM_PRICE_MSTR
join i in _odb.ITEM_MSTR on i.ITM_ID equals i.ITM_ID
select new ItemModel
{
itemid = i.ITM_ID,
itemname = i.ITM_DESC,
itemprice = ip.ITM_PRICE,
defaultflag = ip.DEFAULT_FL,
startdate = DbFunctions.TruncateTime(ip.START_DT),
enddate = DbFunctions.TruncateTime(ip.END_DT),
createddt = i.CREA_DT
};
prices = prices.Where(i => i.itemid.ToLower().Contains(item_Id.ToLower()));
prices = prices.OrderByDescending(i => i.itemprice);
var vm = new ItemViewModel();
vm.Items = prices.ToPagedList(pageNumber, pageSize);
return PartialView("_ViewItemPrice", vm);
}
Q#2: When I return a PartialView in Controller using PartialViewResult, who's going to receive and display it in the View? I ran the code, but nothing is being displayed. I think I still lack codes in View to receive the returned PartialView in Controller
Assuming you have many items with different item_Id and you want to show the modal dialog when this item is clicked. You should be listen to the click event on the element, make an ajax call and get the response (partial view result) and use that to build your modal dialog content.
Assuming your main view has code like this
<table>
#foreach (var item in Model.Items)
{
<tr>
<td>#item.itemname</td>
<td><a href="#Url.Action("RetrieveItemPrice",new { item_Id = itemId})"
class="modal-link" >#item.itemname</a>
</td>
</tr>
}
</table>
<!-- The below code is for the modal dialog -->
<div id="modal-container" class="modal fade" tabindex="-1" role="dialog">
X
<div class="modal-content">
<div class="modal-body"></div>
</div>
This will generate links with css class modal-link for each item in the table. The href value of the links will be like YourControllerName/RetrieveItemPrice?item_id=123(123 will be replaced with actual itemid) Now listen to the click event on these, make an ajax call to the href attribute value of these links and use the response for populating the modal dialog content.
$(function () {
$('body').on('click', '.modal-link', function (e) {
e.preventDefault();
$("#modal-container").remove();
$.get($(this).attr("href"), function (data) {
$('<div id="modal-container" class="modal fade">
<div class="modal-content" id="modalbody">'
+ data + '</div></div>').modal();
});
});
});
This code will replace the entire content of the modal with the partial view result coming from the RetrieveItemPrice action method. That means you need to include the necessary markup needed for the modal header and footer(with buttons) in the _ViewItemPrice partial view.
A#1: the code calling #Html.Action is executed on server-side, at that phase the html document has not been sent to client-side so you don't have to look for a way to retrieve element value. You can pass it directly to the call, instead, because the model used for rendering the view (including the element) should be accessible to the code in the modal.
If you place the modal markups right inside the view, you definitely can get #Model.ItemId, for example.
If you place the modal in a partial view, you can pass item id via ViewBag:
#Html.Partial("Modal", null, new ViewDataDictionary{{"ItemId", Model.ItemId}})
then use it in the modal markups:
#Html.Action("RetrieveItemPrice", new { item_Id = ViewBag.ItemId })
A#2: you should try if [ChildActionOnly] makes the action RetrieveItemPrice works.

Categories

Resources