I'm having a problem getting a form to work without javascript being enabled.
This should be enough to go on, ask if you need to know anything else - I don't want to just put the whole solution up here!
~/Views/_ViewStart.cshtml:
#{ Layout = "~/Views/Shared/Layout.cshtml"; }
~/Views/Shared/Layout.cshtml:
#using System.Globalization; #{ CultureInfo culture = CultureInfo.GetCultureInfo(UICulture); }<!DOCTYPE html>
<html lang="#culture.Name" dir="#(culture.TextInfo.IsRightToLeft ? "rtl" : "ltr")">
<head>
<title>AppName :: #ViewBag.Title</title>
<link href="#Url.Content("~/favicon.ico")" rel="shortcut icon" type="image/x-icon" />
<link href="#Url.Content("~/apple-touch-icon.png")" rel="apple-touch-icon" />
<link href="#Url.Content("~/Content/css/site.css")" rel="stylesheet" type="text/css" />
<script src="#Url.Content("~/Content/js/jquery-1.6.min.js")" type="text/javascript"></script>
<script src="#Url.Content("~/Content/js/jquery.unobtrusive-ajax.min.js")" type="text/javascript"></script>
<script src="#Url.Content("~/Content/js/jquery.validate.min.js")" type="text/javascript"></script>
<script src="#Url.Content("~/Content/js/jquery.validate.unobtrusive.min.js")" type="text/javascript"></script>
<script src="#Url.Content("~/Content/js/app.js")" type="text/javascript"></script>
#RenderSection("SectionHead", false)
</head>
<body>
<div id="page-container">
<div id="nav">
<div id="nav-user">
#{ Html.RenderAction("LoginStatus", "Account"); }
#{ Html.RenderPartial("CultureSelector"); }
</div>
</div>
<div id="page-content">
<h2>#ViewBag.Title</h2>
#RenderBody()
</div>
</div>
</body>
</html>
~/Views/Account/Index.cshtml:
#model AccountFilterModel
#{
ViewBag.Title = "Account Home";
var loadingId = "loading" + new Random().Next();
Model.FilterFormId = "filter-account-form";
}
#using (Ajax.BeginForm("List", "Account", Model, new AjaxOptions { UpdateTargetId = "result-list", LoadingElementId = loadingId }, new { id = "filter-account-form" })) {
<!-- form controls and validation summary stuff -->
<input id="filter" type="submit" value="Filter" />
<span id="#loadingId" style="display: none">
<img src="#Url.Content("~/Content/images/ajax-loader.gif")" alt="Loading..." />
</span>
}
<div id="result-list">
#{ Html.RenderAction("List", Model); }
</div>
~/Views/Account/List.cshtml:
#model FilterResultModel
#helper SortLink(AccountSort sort, SortDirection dir) {
string display = (dir == SortDirection.Ascending ? "a" : "d"); // TODO: css here
if (Model.Filter.SortBy != null && ((AccountSortModel)Model.Filter.SortBy).Sort == sort && dir == Model.Filter.SortOrder) {
#:#display
} else {
FilterModel fm = new FilterModel(Model.Filter);
fm.SortBy = AccountSortModel.SortOption[sort];
fm.SortOrder = dir;
#display
}
}
#if (Model.Results.Count > 0) {
var first = Model.Results.First();
<table>
<caption>
#string.Format(LocalText.FilterStats, Model.FirstResultIndex + 1, Model.LastResultIndex + 1, Model.CurrentPageIndex + 1, Model.LastPageIndex + 1, Model.FilteredCount, Model.TotalCount)
</caption>
<thead>
<tr>
<th>
#Html.LabelFor(m => first.Username)
<span class="sort-ascending">
#SortLink(AccountSort.UsernameLower, SortDirection.Ascending)
</span>
<span class="sort-descending">
#SortLink(AccountSort.UsernameLower, SortDirection.Descending)
</span>
</th>
<!-- other table headers -->
</tr>
</thead>
<tbody>
#foreach (AccountModel account in Model.Results) {
<tr>
<td>#Html.EncodedReplace(account.Username, Model.Filter.Search, "<span class=\"filter-match\">{0}</span>")</td>
<!-- other columns -->
</tr>
}
</tbody>
</table>
Html.RenderPartial("ListPager", Model);
} else {
<p>No Results</p>
}
Relevant part of AccountController.cs:
public ActionResult Index(AccountSort? accountSort, FilterModel model = null) {
FilterModel fm = model ?? new FilterModel();
if (accountSort.HasValue) fm.SortBy = AccountSortModel.SortOption[accountSort.Value];
return View(fm);
}
public ActionResult List(AccountSort? accountSort, FilterModel model = null) {
FilterModel fm = model ?? new FilterModel();
if (accountSort.HasValue) fm.SortBy = AccountSortModel.SortOption[accountSort.Value];
return Request.IsAjaxRequest() ? (ActionResult)PartialView("List", Service.Get(fm)) : View("Index", model);
}
With javascript enabled, this works fine - the content of div#result-list is updated as expected.
If I don't do the Request.AjaxRequest() and just return the PartialView, then with javascript disabled I get a page with just the content of the results on it. If I have the code as above, then I get a StackOverflowException.
How do I get this to work?
Solution
Thanks to #xixonia, I discovered the problem - here is my solution:
public ActionResult List(AccountSort? accountSort, FilterModel model = null) {
FilterModel fm = model ?? new FilterModel();
if (accountSort.HasValue)
fm.SortBy = AccountSortModel.SortOption[accountSort.Value];
if (Request.HttpMethod == "GET")
return PartialView("List", Service.Get(fm));
if (Request.HttpMethod == "POST")
return Request.IsAjaxRequest() ? (ActionResult) PartialView("List", Service.Get(fm)) : RedirectToAction("Index", model);
return new HttpStatusCodeResult((int) HttpStatusCode.MethodNotAllowed);
}
You can use the following extension method to determine if the request is an ajax request
Request.IsAjaxRequest()
If it is, you can return a partial view, otherwise you can return a full view or redirect.
if(Request.IsAjaxRequest())
{
return PartialView("view", model);
}
else
{
return View(model);
}
edit: here's the problem:
The "List" is returning the "Index" view when the request is not an AJAX request:
public ActionResult List(AccountSort? accountSort, FilterModel model = null) {
FilterModel fm = model ?? new FilterModel();
if (accountSort.HasValue) fm.SortBy = AccountSortModel.SortOption[accountSort.Value];
return Request.IsAjaxRequest() ? (ActionResult)PartialView("List", Service.Get(fm)) : View("Index", model);
}
The "Index" view is rendering the "List" action:
#{ Html.RenderAction("List", Model); }
AKA: Recursion.
You need to engineer a way to display your list without drawing the index page, or make your index page draw a partial view with your list modal as a parameter.
Related
I are trying to develop a shareable widget.
I am developing by using razor.view, razor.page and razor.component (project templates are Razor Class Library and ASP.NET Core 6 MVC).
_Imports.razor under RCL Project is as follows:
#using System.Net.Http
#using Microsoft.AspNetCore.Authorization
#using Microsoft.AspNetCore.Components.Authorization
#using Microsoft.AspNetCore.Components.Forms
#using Microsoft.AspNetCore.Components.Routing
#using Microsoft.AspNetCore.Components.Web
#using Microsoft.JSInterop
#using System.IO
#using CarRentalWidget.Models.DBEntities.Franchises
#using CarRentalWidget.Models.ViewModels.GooogleGeoCodes
AutoCompleteLocationsComponent.razor is as follows:
#using System.Net.Http
#using System.Net.Http.Json
#using System.Threading.Tasks
#inject HttpClient Http
#namespace CarRentalWidget.RCL.CarWidgetUI.Pages
<div>
<input
type="text"
id="TxtBxPickUpLoc"
class="postcode tf-form-control"
placeholder="Please Enter Postcode or Town"
value="#inputValue"
#onchange="DoChangeLocation"
autoComplete="off"
/>
#if(!string.IsNullOrWhiteSpace(inputValue))
{
<a className="location" href="#" id="branch-selector" onClick={onClearLocations}></a>
}
else if (string.IsNullOrWhiteSpace(inputValue))
{
<a className="location empty" href="#" id="branch-selector" onClick={onClearLocations}></a>
}
</div>
<div class="sautocomplete-content-container tk-search-drop-wrapper ac-drop-active">
<div class="sautocomplete-content tk-search-drop">
<div class="branch-info">
<ul id="LocationSuggestions" class="suggestions">
#if (locationData != null && locationData.Count() > 0)
{
#foreach (FranchiseWebInquiry suggestion in locationData!)
{
// Flag the active suggestion with a class
if (index == activeSuggestionIndex)
{
className = "suggestion-active";
}
<li class="#className" key="#index + #suggestion.FranchiseName" onClick="onClick(suggestion)">
<a pickupid="#suggestion.PickupId + #suggestion.FranchisesId" franchisesid="#suggestion.FranchisesId" subofficeid="#suggestion.SubOfficeId" href="#">
<span class="locName">#suggestion.FranchiseName</span>
<span class="locDetails">#getAddress(suggestion)
</span>
</a>
</li>
++index;
}
}
</ul>
</div>
</div>
</div>
#code {
private string inputValue = "";
private string className = "";
private int activeSuggestionIndex;
private int index = 0;
private FranchiseWebInquiry[]? locationData;
private bool getError;
private bool shouldRender;
protected override bool ShouldRender() => shouldRender;
private GoogleGeocode? currentMapItems;
private async Task<GoogleGeocode?> loadGoogleGeoCodeData(string postCodeOrTown)
{
currentMapItems = await Http.GetFromJsonAsync<GoogleGeocode?>
("https://maps.googleapis.com/maps/api/geocode/json?types=geocode&language=en&key=mykey&address=" + postCodeOrTown);
return currentMapItems;
}
private async Task getLocationsApi(string postCodeOrTown)
{
await loadGoogleGeoCodeData(postCodeOrTown);
Result? serviceResult = currentMapItems!.Results!.FirstOrDefault();
Location? locDetail = serviceResult != null && serviceResult.Geometry != null ? serviceResult.Geometry.Location:null;
double providedLattitude = locDetail != null ? locDetail.Lat : 0;
double providedLongitude = locDetail != null ? locDetail.Lng : 0;
locationData = await Http.GetFromJsonAsync<FranchiseWebInquiry[]?>
("https://localhost:7177/api/CarRental/allfranchises/?postCodeOrAddress=" + postCodeOrTown + "&lattitude=" + providedLattitude + "&longitude=" + providedLongitude);
}
private async void DoChangeLocation(ChangeEventArgs e)
{
inputValue = e.Value!.ToString();
if (inputValue!.Length >= 5)
{
await getLocationsApi(inputValue);
}
Console.WriteLine("It is definitely: " + inputValue);
}
private string getAddress(FranchiseWebInquiry suggestion)
{
//debugger;
string localAddress = "";
if (suggestion != null)
{
if (!string.IsNullOrWhiteSpace(suggestion.Address1))
{
localAddress = suggestion.Address1 + " , ";
}
if (!string.IsNullOrWhiteSpace(suggestion.Address2))
{
localAddress += suggestion.Address2 + " , ";
}
if (!string.IsNullOrWhiteSpace(suggestion.Address3))
{
localAddress += suggestion.Address3 + " , ";
}
if (!string.IsNullOrWhiteSpace(suggestion.Town))
{
localAddress += suggestion.Town + "- " + (!string.IsNullOrWhiteSpace(suggestion.PostCode) ? "(" + suggestion.PostCode + "), ":"");
}
if (!string.IsNullOrWhiteSpace(suggestion.PrimaryContact))
{
localAddress += suggestion.PrimaryContact;
}
}
return localAddress;
}
}
and Index.cshtml is as follows:
#page "/car-index"
#model CarRentalWidget.RCL.CarWidgetUI.Pages.IndexPageModel
<!DOCTYPE html>
<html>
<head>
<meta name="viewport" content="width=device-width" />
<title>Car Rental Widget</title>
</head>
<body>
<div class="widget-wrapper">
<div class="main-heading">
<h1>
Test 1
</h1>
</div>
<div class="widget-slider">
<div class="row step-row">
<div class="col-12">
<div class="pickup-location tf-search-group">
<div class="label-location tf-search-label">pick up location</div>
<div id="PickUpLocationControlId" class="input-group-location tf-search-field">
<div class="card">
#(await Html.RenderComponentAsync<CarRentalWidget.RCL.CarWidgetUI.Pages.AutoCompleteLocationsComponent>
(RenderMode.ServerPrerendered/*,new { Data="I came from Index",style= "badge-danger" }*/))
</div>
</div>
</div>
</div>
</div>
</div>
</div>
</body>
</html>
Now I just added the reference in my ASP.NET Core 6 MVC project and open the browser and tried this url in the browser.
https://localhost:7177/car-index
Everything is working as expected. No issue till so far.
Now I am trying to consume this through a plain html (and Javascript/jQuery).
My client end application request is as follows:
<!DOCTYPE html>
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.6.0/jquery.min.js"></script>
<script>
$(document).ready(function(){
$("button").click(function(){
$.ajax({url: "https://localhost:7177/car-index", success: function(result){
$("#CarWidget").html(result);
}});
});
});
</script>
</head>
<body>
<div id="CarWidget">
</div>
</body>
</html>
See I tried with above script, there is no error code even in Browser Network tab.
Why?
For detailed understanding, you can follow this link as well
https://learn.microsoft.com/answers/comments/872715/view.html
and these links
https://learn.microsoft.com/en-us/aspnet/core/razor-pages/ui-class?view=aspnetcore-6.0&tabs=visual-studio
https://learn.microsoft.com/en-us/aspnet/core/blazor/components/class-libraries?view=aspnetcore-6.0&tabs=visual-studio
I have two dropdowns in the view but one relies on the selected value from the other. But how could i load values into the second dropdown after selecting a value from the other? The second dropdown should load values basing on the id selected from the other dropdown.
<div class="form-group">
<label asp-for="BankId" class="control-label col-xs-2"></label>
<div class="col-xs-4">
<select class="form-control" asp-for="BankId" asp-items=#bank>
<option>--- select bank ---</option></select>
</div>
</div>
<div class="form-group">
<label asp-for="BankBranchId" class="control-label col-xs-2"></label>
<div class="col-xs-4">
<select class="form-control" asp-for="BankBranchId" asp-items=#bankbranches>
<option>--- select bank branch ---</option></select>
</div>
</div>
BankBranch should fill values basing on the bank selected from up
Below is example for bank and branches.
you can try out something
<!DOCTYPE html>
<html>
<head>
<meta name="viewport" content="width=device-width"/>
<title>Index</title>
</head>
<body>
#using (Html.BeginForm("Index", "Home", FormMethod.Post))
{
#Html.DropDownListFor(m => m.bank, Model.bank, "Please select", new { onchange = "document.forms[0].submit();" })
<br/>
<br/>
#Html.DropDownListFor(m => m.branches, Model.branches, "Please select", new { disabled = "disabled" })
<br/>
<br/>
<input type="submit" value="Submit"/>
}
<script src="~/Scripts/jquery-1.10.2.min.js"></script>
<script type="text/javascript">
$(function () {
if ($("#bank option").length > 1) {
$("#bank").removeAttr("disabled");
}
if ($("#branches option").length > 1) {
$("#branches").removeAttr("disabled");
}
if ($("#bank").val() != "" && $("#branches").val() != "") {
var message = "Bank: " + $("#CountryId option:selected").text();
message += "\nbranck: " + $("#StateId option:selected").text();
alert(message);
}
});
</script>
</body>
</html>
public class HomeController : Controller
{
// GET: Home
public ActionResult Index()
{
// populate bank values
foreach (var bankent in entities.bank)
{
model.bank.Add(new SelectListItem { Text = bankent.bank, Value = bankent.id.ToString() });
}
return View(model);
}
[HttpPost]
public ActionResult Index(int? bank)
{
// populate bank values
foreach (var bankent in entities.bank)
{
model.bank.Add(new SelectListItem { Text = bankent.bank, Value = bankent.id.ToString() });
}
if (bank.HasValue)
{
//populate branches based on bank id
foreach (var state in branches)
{
model.branches.Add(new SelectListItem { Text = state.branches, Value = state.StateId.ToString() });
}
}
return View(model);
}
}
for more detail check out Populate one DropDownList based on another DropDownList selected value in ASP.Net MVC
my view statement shows error that " for each statement cannot operate on variables of type public definition for 'get enumerator' "
I defined all objects in model and view models. still i get this error. any solution for this?
MY VIEW:
#using Edi.ViewModel
#model viewmodel
#{
<link rel="stylesheet" type="text/css" href="~/Content/style.css" />
Layout = null;
}
<!DOCTYPE html>
<html lang="en">
<head>
<link href="~/Content/Site.css" rel="stylesheet" />
<link href="~/Content/bootstrap.min.css" rel="stylesheet" />
<link href="~/Content/bootstrap.css" rel="stylesheet" />
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css">
</head>
<body>
<form id="form1" name="zoo">
<div class="med">
<pre>
<fieldset id="field1">
<legend>Bill Date Range</legend>
<input type="checkbox">After <input type="date" /> <input type="checkbox">Before <input type="date" />
</fieldset>
<fieldset id="field2">
<legend>Options</legend>
<label>Facility</label> #Html.DropDownListFor(Model => Model.Facility, Model.Facility, "Select Facility", new { style = "width:200px; height :30px" })
<label>Ins Queue</label> #Html.DropDownListFor(Model => Model.InsQueue, Model.InsQueue, "Select InsQueue", new { style = "width:200px; height:30px" })
Claim type <select style="width: 100px; height:30px"><option value="ALL">All</option><option value="NEW">New</option><option value="RESUBMIT">Resubmit</option></select>
</fieldset>
<pre>
<label>No of Bills Selected </label><input type="text" size="1" /> <label> EDI send To </label> #Html.DropDownListFor(Model => Model.EdiSendTo, Model.EdiSendTo, "Select Edi", new { style = "width:200px; height :30px" }) <button type="button" onclick="">Select All</button> <button type="reset" onclick="">Refresh</button> <button type="button" onclick="">Clear All</button> <button type="button" onclick="">Edit Bill</button>
</pre>
<table id="myTable">
<tr class="hd">
<th>visit</th>
<th>billno</th>
<th>patient</th>
<th>providername</th>
<th>insname</th>
<th>payby</th>
<th>inscode</th>
<th>user</th>
<th>claimtype</th>
</tr>
-------------------#foreach (var items in Model)------------------------------
{
<tr onclick="javascript:showRow1(this);">
<td>#items.visit</td>
<td>#items.billno</td>
<td>#items.Patient</td>
<td>#items.ProviderName</td>
<td>#items.InsName</td>
<td>#items.PayBy</td>
<td>#items.InsCode</td>
<td>#items.User</td>
<td>#items.ClaimType</td>
</tr>
}
</table>
</div>
</form>
</body>
</html>
MY CONTROLLER:
namespace Edi.Controllers
{
public class HomeController :Controller
{
// GET: Home
public ActionResult Index()
{
mbill mt = new mbill();
billing db = new billing();
viewmodel vm = new viewmodel();
vm.Facility = db.Add1();
vm.EdiSendTo = db.Add2();
vm.InsQueue = db.Add3();
List<mbill> itemlist = new List<mbill>();
itemlist = db.Index();
return View("Index",vm);
}
}
}
MY MODEL:
public List<mbill> Index()
{
List<mbill> itemList = new List<mbill>();
connection();
SqlCommand cmd = new SqlCommand("procGetEDIBills", con);
cmd.CommandType = CommandType.StoredProcedure;
con.Open();
SqlDataAdapter sd = new SqlDataAdapter(cmd);
DataTable dt = new DataTable();
sd.Fill(dt);
mbill item = new mbill();
using (SqlDataReader sdr = cmd.ExecuteReader())
{
mbill io = new mbill();
while (sdr.Read())
{
io = new mbill();
io.visit = sdr["VisitDate"].ToString();
io.billno = sdr["Billno"].ToString();
io.Patient = sdr["PatientName"].ToString();
io.ProviderName = sdr["ProviderName"].ToString();
io.InsName = sdr["InsuranceName"].ToString();
io.PayBy = sdr["BillPayBy"].ToString();
io.InsCode = sdr["InsuranceId"].ToString();
io.User = sdr["QueueByUser"].ToString();
io.ClaimType = sdr["ClaimType"].ToString();
itemList.Add(io);
}
}
con.Close();
return itemList;
}
}
if i delete #using Edi.ViewModel, #model viewmodel, on view then foreach error disappears and dropdownlistfor shows does not contain definition for dropdownlistfor error.
I'm using C# asp.net mvc4 and trying to do ajax search. But ther is error and it says " The resource cannot be found.".
What I'm doing wrong?
Controller
//Search
[HttpPost]
public ActionResult ContractSearch(string Name)
{
var contracts = db.Contracts.Include(c => c.DocType).Include(c => c.CreditType).Include(c => c.Bank).Include(c => c.UserProfile).Where(c => c.FirstName.Equals(Name));
return View(contracts.ToList());
}
View
#model IEnumerable<CreditoriyaApp.Models.Contract>
#{
ViewBag.Title = "Index";
}
<div>
#using (Ajax.BeginForm("ContractSearch", "Contract", new AjaxOptions { UpdateTargetId = "searchresults" }))
{
<input type="text" name="Name" />
<input type="submit" value="Search" />
}
<div id="searchresults">
#if (Model != null && Model.Count()>0)
{
<ul>
#foreach (var item in Model)
{
<li>#item.FirstName</li>
}
</ul>
}
</div>
Error
Server Error in '/' Application.
The resource cannot be found.
Description: HTTP 404. The resource you are looking for (or one of its dependencies) could have been removed, had its name changed, or is temporarily unavailable. Please review the following URL and make sure that it is spelled correctly.
Requested URL: /Contract/ContractSearch
Add the below in your controller. Then your error will be corrected.
public ActionResult ContractSearch()
{
return View();
}
for searching you can try something like below example.
Model:
public class Person
{
public string Name { get; set; }
public string Country { get; set; }
}
Controller:
public ActionResult SearchPerson()
{
return View();
}
[HttpPost]
public ActionResult SearchPerson(string searchString)
{
System.Collections.Generic.List<Person> lst = new List<Person>();
lst.Add(new Person { Name = "chamara", Country = "Sri Lanka" });
lst.Add(new Person { Name = "Arun", Country = "India" });
if (!string.IsNullOrEmpty(searchString))
{
lst = lst.AsEnumerable().Where(r => r.Name.Contains(searchString)).ToList();
}
string result = string.Empty;
result = "<p>Search Result<p>";
foreach (Person item in lst)
{
result = result + "<p> Names is: " + item.Name + " and Country is:" + item.Country + "<p>";
}
return Content(result, "text/html");
}
View:
#model IEnumerable<Mvc4Test.Models.Person>
#{
Layout = null;
}
<!DOCTYPE html>
<html>
<head>
<meta name="viewport" content="width=device-width" />
<title>SearchPerson</title>
<script src="#Url.Content("~/Scripts/jquery-1.7.1.min.js")" type="text/javascript"></script>
<script src="#Url.Content("~/Scripts/jquery.unobtrusive-ajax.js")" type="text/javascript"></script>
<script src="#Url.Content("~/Scripts/jquery.validate.js")" type="text/javascript"></script>
<script src="#Url.Content("~/Scripts/jquery.validate.unobtrusive.js")" type="text/javascript"></script>
</head>
<body>
#using (Ajax.BeginForm("SearchPerson", "Search", new AjaxOptions { HttpMethod = "Post", UpdateTargetId = "searchresults" }))
{
#Html.TextBox("searchString")
<input type="submit" value="Search" />
}
<div id="searchresults">
</div>
</body>
</html>
I have a list of Products. Each line has 'Delete' action. When I try to delete any row everything is true, but after second deleting ajax confirmation comes twice. Please help.
There are product list view.
#model IEnumerable<Domain.Entities.Product>
#{
ViewBag.Title = "Products";
Layout = "~/Views/Shared/_AdminLayout.cshtml";
}
<h1>Products</h1>
<table class="Grid">
<tr>
<th>Name</th>
<th>Description</th>
<th>Price</th>
</tr>
#foreach (var item in Model) {
<tr>
<td>#item.Name</td>
<td>#item.Description</td>
<td>#item.Price</td>
<td>
#using (Ajax.BeginForm("DeleteProduct", "Admin",
new AjaxOptions {
Confirm="Product was deleted!",
UpdateTargetId="DeleteProduct"
}))
{
#Html.Hidden("Id", item.Id)
<input type="image" src="../Images/Icons/DeleteIcon.jpg" />
}
</td>
</tr>
}
</table>
There are AdminController
[Authorize]
public class AdminController : Controller
{
private IProductRepository productRepository;
public AdminController(IProductRepository productRepository)
{
this.productRepository= productRepository;
}
public ViewResult Products()
{
return View(productRepository.Products);
}
[HttpPost]
public ActionResult DeleteProduct(int id)
{
Product prod = productRepository.Products.FirstOrDefault(p => p.Id == id);
if (prod != null)
{
productRepository.DeleteProduct(prod);
TempData["message"] = string.Format("{0} was deleted", prod.Name);
}
return RedirectToAction("Products");
}
}
And finally _AdminLayout.cshtml
<html>
<head>
<title>#ViewBag.Title</title>
<link href="#Url.Content("~/Content/Admin.css")" rel="stylesheet" type="text/css" />
<script src="#Url.Content("~/Scripts/jquery-1.4.4.min.js")" type="text/javascript"></script>
<script src="#Url.Content("~/Scripts/jquery.unobtrusive-ajax.js")" type="text/javascript"></script>
</head>
<body>
<div id="DeleteProduct">
#if (TempData["message"] != null) {
<div class="Message">#TempData["message"]</div>
}
#RenderBody()
</div>
</body>
</html>
The problem here is that you are calling the DeleteProduct action with AJAX and this action is performing a Redirect to the Products action. Except that the Products action is returning a full HTML instead of a partial. So you get the jquery.unobtrusive-ajax.js injected twice into your DOM. So you get 2 confirmations on the second delete, 3 on the third and so on.
So start by defining a partial containing the table records (~/Views/Admin/_Products.cshtml):
#model IEnumerable<Domain.Entities.Product>
<div>#ViewData["message"]</div>
<table class="Grid">
<thead>
<tr>
<th>Name</th>
<th>Description</th>
<th>Price</th>
</tr>
</thead>
<tbody>
#foreach (var item in Model)
{
<tr>
<td>#item.Name</td>
<td>#item.Description</td>
<td>#item.Price</td>
<td>
#using (Ajax.BeginForm("DeleteProduct", "Admin",
new AjaxOptions {
Confirm = "Are you sure you wanna delete this product?",
UpdateTargetId = "products"
})
)
{
#Html.Hidden("Id", item.Id)
<input type="image" src="#Url.Content("~/Images/Icons/DeleteIcon.jpg")" alt="Delete" />
}
</td>
</tr>
}
</tbody>
</table>
and then modify your main view so that it uses this partial:
#model IEnumerable<Product>
#{
ViewBag.Title = "Products";
Layout = "~/Views/Shared/_AdminLayout.cshtml";
}
<h1>Products</h1>
<div id="products">
#Html.Partial("_Products")
</div>
and finally modify your DeleteProduct controller action so that it no longer does any redirects but returns the partial instead after deleting the record:
[HttpPost]
public ActionResult DeleteProduct(int id)
{
Product prod = productRepository.Products.FirstOrDefault(p => p.Id == id);
if (prod != null)
{
productRepository.DeleteProduct(prod);
ViewData["message"] = string.Format("{0} was deleted", prod.Name);
}
return PartialView("_Products", productRepository.Products);
}
You have everything funneled through a single AJAX operation, so the click of delete is finding two items to delete on the second click. The way to handle this is work some magic on resetting the bound items so either a) the deleted item is set up to show it is already deleted once confirmed or b) rebinding the entire set of items after a delete to get rid of the item that has been deleted.
As long as you continue to have an item that the client believes has not been deleted, you will continue to "delete both" each time you click.