How to load custom content to jquery dialog from html table - ajax

I have a list of images presented in a table format with an update option to edit the image/description in a dialog box.
I have implemented a javascript function loadDialog to dynamically pass the id to the dialog.
However, the editor complains that id is not recognized in the line below:
$(this).load("#Url.Action("UpdateProjectImageDetail", new { ProjectId = id})") ;
Following are the script and html files.
$(function(){
$('#OpenImgDialog').dialog({
autoOpen: false,
width: 400,
resizable: false,
title: 'Add/Update Image',
modal: true,
buttons: {
"Cancel": function () {
$(this).dialog("close");
}
}
});
});
function loadDialog(id) {
var Pid = id;
$("#OpenImgDialog").dialog({
open: function (event, ui) {
var Pid = id;
$(this).load("#Url.Action("UpdateProjectImageDetail", new { ProjectId = id})") ;
}
});
$('#OpenImgDialog').dialog('open');
}
Here is my HTML
<table>
<tr>
<th>
Image
</th>
<th>
Description
</th>
<th></th>
</tr>
#foreach (var item in Model.Images) {
<tr>
<td>
<img src ="#item.ImageString" width="200" height="100" />
</td>
<td>
#Html.DisplayFor(modelItem => item.Description)
</td>
<td>
<a class="UpdateImage" href="#" onclick="loadDialog(#item.Id)">Edit</a>
#Html.ActionLink("Delete", "Delete", new { id=item.Id })
</td>
</tr>
}
</table>
How can I pass arguments from javascript to Url.Action?
Or is there a better approach to solving this problem?
Any demo/reference/solution will be helpful for me.
Thanks in advance!

Appologies I think I know what you are after.
in the
$(this).load("#Url.Action("UpdateProjectImageDetail", new { ProjectId = id})") ;
the
#Url.Action("UpdateProjectImageDetail", new { ProjectId = id})
is running server side you need to pass in the id from the client to the server. which meands it should look something like this
function loadDialog(id) {
var Pid = id;
$("#OpenImgDialog").dialog({
open: function (event, ui) {
var Pid = id;
var url = '#Url.Action("UpdateProjectImageDetail")?ProjectId=' + id;
$(this).load(url) ;
}
});
$('#OpenImgDialog').dialog('open');
}

#Url.Action() is server side code, so you can't pass a client side (js) variable to it.
Without looking too closely, you could probably do something like:
$(this).load("#Url.Action(...)" + "?ProjectId=" + id);
There's probably a more elegant solution, but that's all I have time for right now... ;)

Related

popup a dialog and submit partial view in asp.net mvc

So what I am trying to do here is that in the View,
when I click on the button, I want to pass some values generated from the foreach loop (in my case Country and City) to the javascript function.
Inside that javascript function, I want to open up a dialog(partial view) by passing those values (countryName, cityName) to the controller.
Hence in my controller, it will pass those values to the partial view which will be appeared as a dialog and can submit the form.
I've tried with the version without the pop-up dialog (it worked), but having a hard time doing it with a dialog. #3 works btw, but I think I am having a trouble with #1 and #2. Any help would be appreciated. Thanks.
View:
#model IEnumerable<test.Models.Employee>
<table class="table">
<tr>
<th>Country</th>
<th>City</th>
<th></th>
</tr>
#foreach (var item in Model) {
<tr>
<td>
#Html.DisplayFor(modelItem => item.Country)
</td>
<td>
#Html.DisplayFor(modelItem => item.City)
</td>
<td>
<button onclick="OpenDialog(item.Country, item.City)">
Open Dialog
</button>
</td>
</tr>
}
</table>
<div id="dialog"></div>
#section Scripts {
#Scripts.Render("~/bundles/jqueryval")
<script src="~/Scripts/jquery-ui-1.12.0.js"></script>
<script>
function OpenDialog(countryName, cityName) {
$('#dialog').dialog({
autoOpen: true,
width: 400,
resizable: false,
title: 'My Table',
modal: true,
open: function(event, ui) {
$(this).load('#Url.Action("getEmployee", "Employee", new
{
country = countryName,
city = cityName
})');
},
buttons: {
"Close": function () {
$(this).dialog("close");
}
}
});
}
</script>
}
Controller:
public ActionResult getEmployee(string country, string city)
{
var viewModel = new EmployeeViewModel()
{
Country = country,
City = city
};
return PartialView("EmployeeDialog", viewModel);
}
Partial View:
#model test.ViewModels.EmployeeViewModel
#using (Html.BeginForm("PostEmployee", "Employee", FormMethod.Post))
{
#Html.AntiForgeryToken()
#Html.HiddenFor(model => model.Country)
#Html.HiddenFor(model => model.City)
#Html.EditorFor(model => model.Comments)
<input type="submit" value="Submit"/>
}
#Url.Action() is razor code and is parsed in the server before its sent to the view. countryName and cityName are javascript variables and do not even exist at that point (they are not in scope). Change the code in the OpenDialog() function to
var url = '#Url.Action("getEmployee", "Employee")';
var data = { country: countryName, city: cityName };
$(this).load(url, data);
As a side note, there is really no need to be calling the server each time to return values that you already have in the view. You could just render the form in the dialog initially (for a default EmployeeViewModel and then in the OpenDialog just set the values of the inputs for properties Country and City, for example $('#Country').val(countryName);

AJAX Post to Update List in View

I have a List in my model. The view is bound to the model. I am trying to populate the List through ajax. And then I have a 'submit' button on the form which should submit the entire model. While submitting the entire model, the list value is 'null'??
I am getting the response data from the controller through Json. The response data is not bound to the model.
<table id="tblTable" style="border-width:1px;border-style:solid" >
<tr style="border-width:1px;border-style:solid">
<th>
#Html.Label("Col1")
</th>
<th>
#Html.Label("Col2")
</th>
</tr>
<tbody>
#if (Model != null && Model.Operations!= null && Model.Operations.Count > 0)
{
foreach (var item in Model.Operations)
{
<tr style="border-width:1px;border-style:solid">
<td style="border-width:1px;border-style:solid">
#Html.DisplayFor(modelItem => item.Col1)
</td>
<td style="border-width:1px;border-style:solid">
#Html.DisplayFor(modelItem => item.Col2)
</td>
</tr>
}
}
</tbody>
</table>
My controller that responds to teh ajax request:
[HttpPost]
public JsonResult UploadFile(HttpPostedFileBase file, Model model)
{
//extract file contents into the operations list
model.Operations = new List<Operations>();
model.Operations.Add(blah..blah)
return Json(model);
}
Issue is, I have to populate the list via ajax, but post the complete model along with the ajax-retrieved data.
Update: JS CODE:
$(document).ready(function () {
$('#fileupload').fileupload({
dataType: 'json',
url: '/Summary/UploadFile',
autoUpload: true,
done: function (e, data) {
var operations = data.result.Operations;
var tbl = $('#tblTable');
$.each(operations, function (key, val) {
$('<tr><td>' + val.col1 + '</td>' + '<td>' +
val.col2 + '</td><tr>').appendTo(tbl);
});
}
}).on('fileuploadprogressall', function (e, data) {
var progress = parseInt(data.loaded / data.total * 100, 10);
$('.progress .progress-bar').css('width', progress + '%');
});
});

Duplicated List of DropdownList when ajax update?

I have a Ajax Jquery function:
function UpdateValue() {
$(document.body).on("change",".quantity", function () {
var ProID = $(this).attr("data");
var Quantity = $(this).val();
$.ajax({
type: "GET", url: "/Cart/UpdateValue",
data: { ProID: ProID, quantity: Quantity },
success: function (data) {
$("#cartbox").html(data);
}
}
);
$.ajaxSetup({
cache: false
});
});
}
call UpdateValue in Cart Controller:
public PartialViewResult UpdateValue(Cart cart,int ProID, int quantity)
{
List<SelectListItem> items = new List<SelectListItem>();
for (int i = 1; i <= 10; i++)
{
items.Add(new SelectListItem { Text = i.ToString(),
Value = i.ToString() });
}
ViewBag.Items = items;
Product product = repository.Products.FirstOrDefault(p => p.ProductID
== ProID);
if (product != null)
{
cart.UpdateItem(product, quantity);
}
CartIndexViewModel ptview = new CartIndexViewModel { Cart = cart,
ReturnUrl = "/" };
return PartialView(ptview);
}
When the ajax function success, it returns UpdateValue View. But the Dropdown List always changes the same in each row. How can i pass the selected value from the Index View after ajax update?
Here is my UpdateValue View Code:
<table id="cartbox">
<thead>
<tr>
<th>Tên hàng</th>
<th>Số lượng</th>
<th>Đơn giá</th>
<th colspan="2" style="width:70px">Thành tiền</th>
</tr>
</thead>
<tbody>
#foreach (var line in Model.Cart.Lines)
{
<tr>
<td>#line.Product.Name
</td>
<td>#Html.DropDownList("Quantity", new SelectList(ViewBag.Items as System.Collections.IList, "Value", "Text", line.Quantity), new { data = line.Product.ProductID, #class = "quantity" })</td>
<td style="color:#3A9504;margin-left:3px">#string.Format("{0:00,0 VNĐ}", line.Product.Price)</td>
<td>#string.Format("{0:00,0 VNĐ}", (line.Quantity * line.Product.Price))</td>
<td align="center" style="width:10px"><img src="#Url.Content("~/Content/Images/delete.png")" style="padding-right:10px" /></td>
</tr>
}
</tbody>
<tfoot>
<tr style="border-top-style:solid;border-top-color:#DFDFDF;border-top-width:1px;">
<td colspan="3" align="right" style="border-right-color:#808080;border-right-style:solid;border-right-width:1px;text-align:right"><b>Tổng tiền:</b></td>
<td style="text-align: center"><b>#string.Format("{0:00,0 VNĐ}", Model.Cart.ComputeTotalValue())</b></td>
<td></td>
</tr>
</tfoot>
</table>
If I understand you correctly then your problem is that after updating the data in the dropdown list you lose the selection in that dropdown list?
If so then you would need to add this to your success handler in JavaScript:
success: function (data) {
$("#cartbox").html(data);
$("#cartbox").find(".quantity").val(Quantity);
}

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 );
}

MVC 3 partialview popup problem

I have been trying to create a pop up window with some details gather from a partialview, but I was not able to do it.
I have followed this example, that is pretty clear, but did not work for me.
MVC-pop up windows
I add my code, maybe someone can see better than me, why is not working.
Thanks in advance, Pablo.
This is the controller
[HttpGet]
[Authorize]
public ActionResult _CustomerDetails(int idAddress)
{
using (CustomerAddressClient client = new CustomerAddressClient())
{
var address = client.CustomerAddress_Read(idAddress);
ViewBag.CustomerAddress = address;
}
return PartialView();
}
Then I have the view with this code
#Ajax.ActionLink("Open popup", "_CustomerDetails", new AjaxOptions { HttpMethod = "GET", UpdateTargetId = "customerdetails2", InsertionMode = InsertionMode.Replace, OnSuccess = "openPopup" })
<div id="customerdetails2" ></div>
$(document).ready(function () {
$("#customerdetails2").dialog({
autoOpen: false,
title: 'Title',
width: 500,
height: 'auto',
modal: true
});
});
function openPopup() {
$("#customerdetails2").dialog("open");
}
and the partial view is just a list of the customer details
<table style="width: 100%;" class="customerTable">
<tr>
<td>Address1</td> <td>#ViewBag.CustomerAddress.idAddress</td>
</tr>
<tr>
<td>Address2</td><td>#ViewBag.CustomerAddress.Address2</td>
</tr>
<tr>
<td>Address3</td><td>#ViewBag.CustomerAddress.Address3</td>
</tr>
<tr>
<td>City</td><td>#ViewBag.CustomerAddress.City</td>
</tr>
<tr>
<td>CompanyName</td><td>#ViewBag.CustomerAddress.CompanyName</td>
</tr>
</Table>
Well, the page keep on displaying in the same container, it won't display a popup.

Resources