I need a button posting to manage deleting process when it is clicked. After clicking the button a bootstrap module will appear and then it will ask us whether we continue or not.All will be done without using @Html.AntiForgeryValidation.Because we can not use it in this case.
First of all, I put a button on my HTML table's row to click on it.You can place it wherever you want.Also, I bind a javascript function which is ShowDeleteModal to call confirmation module.
<div class='btn-group'>
<button type='button' class='btn btn-danger btn-sm' onclick="ShowDeleteModal('Log', 'Delete', '@Model.Id' )">
<span class='glyphicon glyphicon-remove'></span> Delete
</button>
</div>
The following image shows how the source HTML code looks in browser(F12)
And here is the ShowDeleteModal function,
function ShowDeleteModal(controller, action, id) {
$("#deleteModal").modal("show");
$("#controllerToDelete").val(controller);
$("#actionToDelete").val(action);
$("#deletedObject").val(id);
}
When the user clicked the button a deleting confirmation message will display to ask will you continue or not?
This message will be inside a bootstrap modal which has three inputs field those are hidden.Those inputs are stored in order of Controller Name(controllerToDelete), Action Name(actionToDelete), and GUID id(deletedObject) is relevant to which object will be deleted. You can see the following code.
<div class="modal fade" id="deleteModal">
<div class="modal-dialog">
<div class="modal-content">
<div class="modal-header">
<button type="button" class="close" data-dismiss="modal">×</button>
<h4 class="modal-title">Deleting Operation</h4>
</div>
<div class="modal-body">
<p>The data temporarily will be deleted, Will you continue?</p>
@{
var deleteRequestVerificationToken = Guid.NewGuid();
TempData["DeleteRequestVerificationToken"] = deleteRequestVerificationToken;
}
<input hidden="hidden" id="DeleteRequestVerificationToken" value="@deleteRequestVerificationToken" />
<input hidden="hidden" id="deletedObject" value="" />
<input hidden="hidden" id="controllerToDelete" value="" />
<input hidden="hidden" id="actionToDelete" value="" />
</div>
<div class="modal-footer">
<button type="button" class="btn btn-default" onclick="ConfirmDelete()" data-dismiss="modal">Continue</button>
<button type="button" class="btn btn-default" data-dismiss="modal">Cancel</button>
</div>
</div>
</div>
</div>
We will post them inside AJAX data.But here I want to be sure that if a post request is coming from somewhere it must be coming from my page or my delete button on the table. It requires a validation system such as MVC's @Html.AntiForgeryToken. We can create our own key on the inside of modal of the deleting to validate the token in Action method after submitting. Place the following code on the page,
@{
var deleteRequestVerificationToken = Guid.NewGuid();
TempData["DeleteRequestVerificationToken"] = deleteRequestVerificationToken;
}
When the page is loaded it sets up a value named 'deleteRequestVerificationToken ' with new GUID.
We store it inside TempData to reach it on the Controller's Action.
Posting process using JQuery with AJAX functionality inside 'ConfirmDelete' function,
function ConfirmDelete() {
var securityToken = $("#DeleteRequestVerificationToken").val();
var controllerToDelete = $("#controllerToDelete").val();
var actionToDelete = $("#actionToDelete").val();
var deletedObject = $("#deletedObject").val();
$.ajax({
type: "POST",
url: "/" + controllerToDelete + "/" + actionToDelete + "?id=" + deletedObject + "&securityToken=" + securityToken,
success: function (response) {
if (response.success == true) {
window.location.href = response.urlToRedirect;
}
}
});
}
In this sample, we assume that we have a Log table and are trying to delete a row from the table.
If you prepare your Action's parameter like the following code you can find out whether we created this ticket or not. If the coming token(securityToken) is equal to the token inside TempData(DeleteRequestVerificationToken) we can keep going on deleting operation.
// POST: Log/Delete/5
[HttpPost]
// [ValidateAntiForgeryToken]
public ActionResult Delete(Guid? id,Guid? securityToken)
{
if (id == null || securityToken == null || TempData.Keys.Any(k => k == "DeleteRequestVerificationToken") || securityToken.ToString() != TempData["DeleteRequestVerificationToken"].ToString())
return Json(new { success = false, message = "Bad Request" }, JsonRequestBehavior.AllowGet);
var model = Get<Log>(id);
if (model != null)
{
model.IsActive = false;
//EditEntity<Log>(model);
//return DeleteEntity<Log>(model, new Route() { Controller = "Log", Action = "Index" });
return Json(new { success = true, urlToRedirect = string.Format("{0}", Url.Action("Index","Log")) } , JsonRequestBehavior.AllowGet);
}
else
{
ModelStateIsNotValid();
return Json(new { success = false , urlToRedirect = string.Format("{0}", Url.Action("Index", "Log")) }, JsonRequestBehavior.AllowGet);
}
}
As you see above, the values that the two keys carry are matched so we can continue on our way.
ASP.NET MVC etiketine sahip kayıtlar gösteriliyor. Tüm kayıtları göster
ASP.NET MVC etiketine sahip kayıtlar gösteriliyor. Tüm kayıtları göster
27 Aralık 2017 Çarşamba
12 Ekim 2016 Çarşamba
Entity Framework: Solution of foreign key constraint may cause cycles or multiple cascade paths?
While I was working on a Project that is ASP.NET MVC using Entity Framework as ORM, I have encountered an error was writen on nuget packet manager console.It says 'Introducing FOREIGN KEY constraint 'FK_dbo.Skill_dbo.Image_ImageId' on table 'Skill' may cause cycles or multiple cascade paths. Specify ON DELETE NO ACTION or ON UPDATE NO ACTION, or modify other FOREIGN KEY constraints.
Could not create constraint or index. See previous errors.' which spotted after I typed 'update-database' commend to update my tables on sql server.
My code contains two class here.As shown below,these tables are Skill and Image.
public class Skill
{
[Key]
public int Id { get; set; }
[MaxLength(50)]
public string Name { get; set; }
[MaxLength(50)]
public string Title { get; set; }
[MaxLength]
public string Description { get; set; }
[MaxLength]
public string Lore { get; set; }
[ForeignKey("ImageId")]
public virtual Image Image { get; set; }
public int ImageId { get; set; }
[MaxLength(20)]
public string ManaCost { get; set; }
[MaxLength(20)]
public string CoolDown { get; set; }
}
public class Image
{
[MaxLength(2083)]
public string OriginalSource { get; set; }
[MaxLength(2083)]
public string ServiceSource { get; set; }
[MaxLength(2083)]
public string AppSource { get; set; }
[Key]
public int Id
{
get;
set;
}
[MaxLength(50)]
public string Name
{
get;
set;
}
public DateTime? CreateDate
{
get;
set;
}
public DateTime? UpdateDate
{
get;
set;
}
}
! SOLUTION : Skill table has a relationship with Image table but Image table does not.Assume that a skill has image data whose id is 77.After that I want to remove the image with id=77,what is gonna happen? Lets discuss what we have until now.We have Skill and Image tables.Inside Skill table there is a skill data that has an image whose id is 77.Inside the Image table we have an image as we said before number 77. I want to remove id's 77 from the Image table.But also we have not NULLABLE image column inside Skill table.The skill row that is connected with the image data will not reach to the image date after removing process.Thus,SQL wont give us permission to do this.Solution is simple. We need to allow image column to be nullable inside Skill table.That give us chance to delete an image data and set skill data's image column NULL.Just do it inside Skill class as you see below.
public int? ImageId{get;set;} or public Nullable<int> ImageId{get;set;}
If your problem looks more complicated than mine or my solution is not fit for your code also I prefer you to check this link out.
9 Aralık 2015 Çarşamba
Breadcrumb (navigation,ekmek kırıntısı) Nedir?
Genellikle web sayfalarında kulanıcılara bulundukları sayfaya ulaşmak için hangi yollardan geçtiklerini hatırlatmaya yönelik bilgi linkidir.Aslında ana dizinden ilgili sayfaya ulaşmak için gezilmesi gereken sayfaları gösterir.Yazılımcılar bu işi meşhur Hansel ve Gretel kardeşlerden öğrenmiştir diyebiliriz.Eski toprak bu iki kardeşin web sayfalarında navigasyon konularına yönelik yaptıkları hizmetleri anmadan geçemeyeceğiz.(Tamam abartıyorum)Annelerinin veya üvey annelerinin yokluk yüzünden aç kalma tehlikesine karşı bulduğu dahiyane fikir sonucu iki kardeş kendilerini babaları tarafından ormana bırakılmış şekilde bulurlar.Ama kardeşler yol boyunca eve(ana sayfaya) dönüş yolunu bulabilmek için cakıl taşları ve ekmek kırıntıları(aha breadcrumbs) ile işaret bırakmışlar.(1)Burada masumların hesaba katmadıkları şey ise ormanda ki masum hayvanların masum bir şekilde kırıntılardan nasiplenmesidir.Tabi kardeşler dönüş yolunu kaybederler ve değişik maceralar yaşarlar.(2)Şaka bir yana bizler bu yapının benzerinin yapımı konusunda kafa yoruyor olacağız.
Breadcrumb(Ekmek kırıntısı) örneği aşağıdaki resimde göründüğü gibidir.Değişik kullanımları mevcuttur.(Genellikle e-ticaret sitelerinde karşılaşabileceğimiz bir yapıdır)
Son zamanlar artık SEO dostu tasarımlar ortaya koyma noktasında yarışa girişen yazılımcılar sayesinde zaten tarayıcımızda gördüğümüz linklerde nerede olduğumuz hakkında bizlere yeterli kırıntıları sunulmaktadır.
Örnek olarak,Dota 2 oyunuyla ilgili istatistik sunan bu sitede(3) Herolar/WitchDoctor/Items kısmından nerede olduğumu anlayabiliyorum.
Benim değinmek istediğim konu ise şu şekilde,elimde bir kategori sistemi var ve buna kategoriler eklemek istiyorum.Her kategorinin üst kategori(Parent Category,bir tane) ve alt kategoriler(Child Categories,birden fazla olabilir) diye alanları mevcuttur.Eğer bir kategorinin üst kategorisi null ise yani yoksa bu kategorimiz saygı değer üst kategoridir.Bunların ekleme veya ilişkilendirilme durumlarına değinmeyeceğim.Bunları hallettiğinizi varsayarak elinizde bir kategori listesinin bulunduğunu ve bu listenin her bir elemanının altında bulunduğu üst kategorisine doğru gezinti menüsünü oluşturmaya çalışacağız.
Elimizde 4 adet kategorinin olduğunu varsayalım.Heroes isimli kategori üst kategorimiz(parent category) olsun.Witch Doctor ve Timbersaw diyede alt kategoriler(child categories) olsun.Bu iki kategorinin parent i Heroes kategorisi olsun ve Witch Doctor bir adet alt(child) kategoriye sahip olsun.Onun adıda Items olsun.
Almamız gereken sonuç :
Heroes kategorisinin breadcrumb linki = Heroes
WitchDoctor kategorisinin breadcrumb linki = Heroes>>WitchDoctor
Timbersaw kategorisinin breadcrumb linki = Heroes>>Timbersaw
Items kategorisinin breadcrumb linki = Heroes>>WitchDoctor>>Items
Biz bu aldığımız sonuçları oluşturacağımız Category nesnelerimizin BreadCrumb(String) alanında saklayacağız.Her nesne kendi ekmek kırıntısıyla eve dönüş yapısını içnide saklayacak.Bunlarıda örnek olarak kategorilerimizin listelendiği tabloda veya diğer aklımıza gelen uygun yerlerde kullanabiliriz.Bunu oluşturan bir fonksiyon tasarlıyoruz.Recursive(4) olarak çalışacak olan bu yapı kategori listemizin her nesnesini dolaşıp o nesnenin üst kategorisini bulana kadar yani üst kategorisi null olan kategoriye denk gelene kadar ekmek kırıntılarını takip etmek olacaktır.Bu işlemi her bir liste elemanı için tekrar edeceğiz.
public class Category : BaseObject
{
string breadcrumbLink;
public Category Parent
{
get
{
return parent;
}
set
{
parent = value;
}
}
public string Name
{
get
{
return name;
}
set
{
name = value;
}
}
public string BreadcrumbLink
{
get
{
return breadcrumbLink;
}
set
{
breadcrumbLink = value;
}
}
List<Category> childList;
public List<Category> ChildList
{
get
{
return childList;
}
set
{
childList = value;
}
}
public string GetBreadcrumbLink(ref int counter, List<Category> categoryList, Category category)
{
if (counter == 0)
{
if (category.Parent == null)
{
BreadcrumbLink += "<strong>" + category.Name + "</strong>(" + category.ChildList.Count + ")";
}
else
{
if (category.ChildList.Count > 0)
BreadcrumbLink += category.Name + "(" + category.ChildList.Count + ")";
else
BreadcrumbLink += category.Name;
}
}
counter++;
if (category.Parent != null)
{
BreadcrumbLink = category.Parent.Name + ">>" + BreadcrumbLink;
GetBreadcrumbLink(ref counter, categoryList, category.Parent);
}
return BreadcrumbLink;
}
}
{
Category parent;
string name;string breadcrumbLink;
public Category Parent
{
get
{
return parent;
}
set
{
parent = value;
}
}
public string Name
{
get
{
return name;
}
set
{
name = value;
}
}
public string BreadcrumbLink
{
get
{
return breadcrumbLink;
}
set
{
breadcrumbLink = value;
}
}
List<Category> childList;
public List<Category> ChildList
{
get
{
return childList;
}
set
{
childList = value;
}
}
public string GetBreadcrumbLink(ref int counter, List<Category> categoryList, Category category)
{
if (counter == 0)
{
if (category.Parent == null)
{
BreadcrumbLink += "<strong>" + category.Name + "</strong>(" + category.ChildList.Count + ")";
}
else
{
if (category.ChildList.Count > 0)
BreadcrumbLink += category.Name + "(" + category.ChildList.Count + ")";
else
BreadcrumbLink += category.Name;
}
}
counter++;
if (category.Parent != null)
{
BreadcrumbLink = category.Parent.Name + ">>" + BreadcrumbLink;
GetBreadcrumbLink(ref counter, categoryList, category.Parent);
}
return BreadcrumbLink;
}
}
Örnek Category sınıfımız yukarıda göründüğü gibidir.İçeriğinde Category sınıfından bir Parent,alt kategoriler için ChildList adında Category Listesi,String tipinde Name alanı(kategori adı) ve BreadcrumbLink adında String tipinde ekmek kırıntısı linkimiz mevcuttur.
foreach (var category in categoryList)
{
int counter = 0;
category.GetBreadcrumbLink(ref counter, categoryList, category);
}
{
int counter = 0;
category.GetBreadcrumbLink(ref counter, categoryList, category);
}
Sistemimizde bulunan bütün kategorilerin geldiği listede her bir kategori nesnesi için yukarıda görüdüğümüz şekilde breadcrumblink alanını doldurabiliriz.
Ben benzer sistemin iki değişik kullanımını örnek vereceğim.ASP.NET MVC kullananlar için tanıdık gelecek bu Controller sayfasında elimde bulunan kategorileri tablo halinde listelenmesini istiyorum.BreadcrumbStyleTable fonksiyonumuz bizlere tablonun satır bilgilerini döndürmektedir.View sayfamızda Html.Raw ile alacağınız bu kısımda tablomuzda kategori adları yerine ilgili kategorinin kategori hiyerarşisindeki konumunu yazdırıyoruz.(Örnek : Futbol>>Takımlar>>Bursaspor).TreeMenu fonksiyonu ise aynı kategori hiyerarşisine ağaç görünümü ile bakmamıza olanak tanıyor.
public class PanelCategoryController : Controller
{
// GET: Category
public ActionResult Index()
{
var categories = Category.CategoryList;
string table = "";
int counter = 0;
BreadcrumbStyleTable(ref counter,ref table,categories);
ViewBag.table = table;
return View(categories);
}
public string BreadcrumbStyleTable(ref int counter,ref string table, List<Category> categoryList, int? parentId = null)
{
if(counter!=categoryList.Count)
table += "<tr>";
counter++;
foreach (var category in categoryList)
{
int? categoryParentId = null;
if (category.Parent != null)
{
categoryParentId = category.Parent.Id;
}
if (categoryParentId == parentId)
{
table += "<td><a href='Category/Details/"+category.Id+"'>" +category.BreadcrumbLink + "</a></td>";
table += " <td><a href='Category/Edit/"+category.Id+"'>Düzenle</a>/<a href='Category/Delete/"+category.Id+"'>Sil</a></tr>";
BreadcrumbStyleTable(ref counter,ref table, categoryList, category.Id);
}
}
return table;
}
public string TreeMenu(ref string table,List<Category> categoryList,int? parentId=null)
{
table += "<ul>";
foreach (var category in categoryList)
{
int? categoryParentId = null;
if(category.Parent!=null)
categoryParentId=category.Parent.Id;
if (categoryParentId == parentId)
{
table += "<li>" + category.Name;
TreeMenu(ref table, categoryList,category.Id);
table += "</li>";
}
}
table += "</ul>";
return table;
}
{
// GET: Category
public ActionResult Index()
{
var categories = Category.CategoryList;
string table = "";
int counter = 0;
BreadcrumbStyleTable(ref counter,ref table,categories);
ViewBag.table = table;
return View(categories);
}
public string BreadcrumbStyleTable(ref int counter,ref string table, List<Category> categoryList, int? parentId = null)
{
if(counter!=categoryList.Count)
table += "<tr>";
counter++;
foreach (var category in categoryList)
{
int? categoryParentId = null;
if (category.Parent != null)
{
categoryParentId = category.Parent.Id;
}
if (categoryParentId == parentId)
{
table += "<td><a href='Category/Details/"+category.Id+"'>" +category.BreadcrumbLink + "</a></td>";
table += " <td><a href='Category/Edit/"+category.Id+"'>Düzenle</a>/<a href='Category/Delete/"+category.Id+"'>Sil</a></tr>";
BreadcrumbStyleTable(ref counter,ref table, categoryList, category.Id);
}
}
return table;
}
public string TreeMenu(ref string table,List<Category> categoryList,int? parentId=null)
{
table += "<ul>";
foreach (var category in categoryList)
{
int? categoryParentId = null;
if(category.Parent!=null)
categoryParentId=category.Parent.Id;
if (categoryParentId == parentId)
{
table += "<li>" + category.Name;
TreeMenu(ref table, categoryList,category.Id);
table += "</li>";
}
}
table += "</ul>";
return table;
}
1)Sefaleti yaşarken ekmek kırıntısından navigasyon olayı iyimiş.Acaba anneleri,"ben sadece pirzola yemek istiyorum kuru ekmek benim yaşam tarzıma uygun değil" diyerek mi çocukları evden kovmayı düşünmüş diye insan kendi kendine sormuyor değil.Yani sorun burada açlık değilde pirzola yiyememek miydi?Çünkü götürüldükleri yerin eve uzaklığı boyunca bırakacakları ekmek kırıntıları için belkide fırın arabasıyla seyahat etmeleri daha makul görünen birşey.
2) https://tr.wikipedia.org/wiki/Hansel_ve_Gretel
3)http://www.dotabuff.com
4)https://en.wikipedia.org/wiki/Recursion_(computer_science) (Özyineleme)
Kaydol:
Kayıtlar (Atom)





