Online Mağaza Projesi Bölüm2
Selamlar;
Öncelikle ürün işlemleri yapılacak admin ekranından başlıyalım. Burada amaç yeni bir ürün girişini yapmak, girilen ürünü düzeltmek ve onaylı bir şekilde silmektir.
View/Home/Admin.cshtml:
1 2 3 4 5 6 7 8 9 10 11 12 |
<h2>Jewellery Store ®</h2> <div class="container"> <div id="fileUpload"> @{Html.RenderPartial("FileUpload");} </div><br /> <div id="productDetail"> @{Html.RenderPartial("ProductDetail", new tblProduct());} </div><br /> <div id="productList"> @{Html.RenderPartial("ProductList", Model);} </div> </div> |
Yukarıda görüldüğü gibi ekranda üç tane partial view vardır. Ürün resmini yüklediğimiz file ajax upload, ürünlerin detayının göründüğü resmi, ismi, fiyatı ve açıklama alanları ile son olarak vitrindeki ürün listesidir.
Views/Shared/FileUpload.cshtml:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 |
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.7/jquery.js"></script> <script src="http://malsup.github.com/jquery.form.js"></script> <script> (function () { $('form').ajaxForm({ success: function () { }, complete: function (xhr) { if (xhr.responseText.trim() != "") { $('#status').prepend('<img id="theImg" src="../Images/' + xhr.responseText + '" width="100" height="100"/>'); $('#ImageUrl').val(xhr.responseText); } } }); })(); </script> @using (Ajax.BeginForm("FileUpload", "Home", new AjaxOptions() { HttpMethod = "POST" }, new { enctype = "multipart/form-data" })) { @Html.AntiForgeryToken() <table> <tr> <td><input type="file" name="files" id="fileUploadControl"></td> <td><input type="submit" value="Upload"></td> <td><div id="status"></div></td> </tr> </table> } |
Yeni Ürün girişinde yukarıda görüldüğü gibi ilk olarak fileupload’u inceleyelim. Form post olunca gideceği action belirlendikten sonra :@using (Ajax.BeginForm(“FileUpload”, “Home”, new AjaxOptions() { HttpMethod = “POST” }, new { enctype = “multipart/form-data” })) güvenlik amaçlı AntiForgeryToken konur. Form ajax ile post olduktan sonra complete durumunda actiondan dönen, image path’i ürün detaydaki resim bilgisine basılır.
HomeController/FileUpload : Post edilen file, images kalsörüne kaydedilir.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 |
[HttpPost] [ValidateAntiForgeryToken] public string FileUpload(IEnumerable<HttpPostedFileBase> files) { string fileName = string.Empty; if (files != null) { foreach (var file in files) { if (file != null && file.ContentLength > 0) { fileName = Path.GetFileName(file.FileName); var path = Path.Combine(Server.MapPath("~/Images"), fileName); file.SaveAs(path); } } } return fileName; } |
Views/Home/Admin.cshtml/saveProduct() function: Kaydet butonuna basılınca aşağıda görüldüğü gibi ürünün jquery post ile yeni kayıt eklenmesi yada güncellenmesi action’larının çağrıldığı functiondır.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 |
function saveProduct(ProductID) { if ($("#btnSubmit").attr('value') == 'Kaydet') { $.post("/Home/Admin", { 'Name': $("#Name").val(), 'ImageUrl': $("#ImageUrl").val(), 'Price': $("#Price").val(), 'Description': $("#Description").val() }, function (isOK) { if (isOK == 1) { $.get("/Home/ProductList", function (listView) { $("#productList").html(listView); messagehub.server.refreshProduct(); }); $.get("/Home/ProductDetail", function (detailView) { $("#productDetail").html(detailView); }); $("#fileUploadControl").val(""); $('#status').html(""); } }); } else { $.post("/Home/AdminUpdate", { 'ID': ProductID, 'Name': $("#Name").val(), 'ImageUrl': $("#ImageUrl").val(), 'Price': $("#Price").val(), 'Description': $("#Description").val() }, function (isOK) { if (isOK == 1) { $.get("/Home/ProductList", function (listView) { $("#productList").html(listView); messagehub.server.refreshProduct(); }); $.get("/Home/ProductDetail", function (detailView) { $("#productDetail").html(detailView); }); $("#fileUploadControl").val(""); $('#status').html(""); } }); } } </script> |
HomeControl/Admin[Get]: Ürün detay ekranı yani ProductDetail, DAL.tblProduct modeli beklemektedir. Aşağıda görüldüğü gibi ilgili model çekilip view’a gönderilir.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 |
[LogAttribute(LogType.Admin,false)] public ActionResult Admin() { if (Session["UserID"] == null) { return RedirectToAction("Login"); } List<DAL.tblProduct> data; using (JewelleryStoreDB dbContext = new JewelleryStoreDB()) { data = dbContext.tblProduct.ToList(); } ViewBag.Title = "Admin"; return View(data); } |
Views/Shared/ProductDetail.cshtml : Ürün detayının göründüğü partial view’dur.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 |
@model DAL.tblProduct <table> <tr> <td>Takının Resmi</td> <td><input type="text" id="ImageUrl" readonly="true" class="form-control" value="@Model.ImageUrl"></td> </tr> <tr> <td>Takının İsmi</td> <td><input type="text" id="Name" class="form-control" value="@Model.Name"></td> </tr> <tr> <td>Takının Fiyatı</td> <td><input type="text" id="Price" class="form-control" value="@Model.Price"></td> </tr> <tr> <td>Takının Açıklaması</td> <td><textarea id="Description" style="width:177px; height:80px" class="form-control">@Model.Description</textarea></td> </tr> <tr> <td><input type="button" onclick="saveProduct(@Model.ID)" value="Kaydet" id="btnSubmit"></td> </tr> </table> |
Yukarıda görüldüğü gibi ürün detay ekranı yani ProductDetail, DAL.tblProduct modeli beklemektedir. Kaydet butonuna basılınca yukarıda görülen Admin’deki saveProduct() function çağrılır. Burada ürün jquery post ile ya güncellenir yada yeni bir ürün girişi yapılır. Yani aşağıda görüldüğü gibi ya /Home/AdminUpdate yada /Home/Admin action çağrılır.
HomeControl/Admin[Post] & AdminUpdate:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 |
[HttpPost] [LogAttribute(LogType.ProductInsert,false)] public int Admin(tblProduct product) { try { using (JewelleryStoreDB dbContext = new JewelleryStoreDB()) { dbContext.tblProduct.Add(product); product.CreatedDate = DateTime.Now; dbContext.SaveChanges(); Session["ProductID"] = product.ID; } return 1; } catch { return 2; } } [LogAttribute(LogType.ProductUpdate,false)] public int AdminUpdate(tblProduct product) { try { using (JewelleryStoreDB dbContext = new JewelleryStoreDB()) { tblProduct tp = dbContext.tblProduct.FirstOrDefault(t => t.ID == product.ID); tp.ImageUrl = product.ImageUrl; tp.Name = product.Name; tp.Price = product.Price; tp.Description = product.Description; dbContext.SaveChanges(); Session["ProductID"] = product.ID; } return 1; } catch { return 2; } } |
Şimdi biraz da yukarda görülen ürün listesini inceleyelim. Aşağıdaki kodlarda görüldüğü gibi partial view model olarak DAL.tblProduct beklemektedir. Ürünle ilgili olarak silme ve düzenleme işleri burada yapılır. Aşağıda görülen Admin ekranındaki editProduct() ve deleteProduct functionları çağrılır.
Views/Shared/ProductList.cshtml :
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 |
@using System.Activities.Statements @model List<DAL.tblProduct> <p><strong><span style="font-size: 14pt;">Jewellery Store Listesi</span></strong></p> <table class="taskList" style="WIDTH: 600px; BORDER-COLLAPSE: collapse" bordercolor="#bbbbbb" cellspacing="0" cellpadding="3" border="1"> <tbody> <tr> <th style="WIDTH: 20%; BACKGROUND-COLOR: #d7e4ef; TEXT-ALIGN: center" scope="col">Adı</th> <th style="WIDTH: 20%; BACKGROUND-COLOR: #d7e4ef; TEXT-ALIGN: center" scope="col">Açıklaması</th> <th style="WIDTH: 20%; BACKGROUND-COLOR: #d7e4ef; TEXT-ALIGN: center" scope="col">Resmi</th> <th style="WIDTH: 20%; BACKGROUND-COLOR: #d7e4ef; TEXT-ALIGN: center" scope="col">Fiyatı</th> <th style="WIDTH: 20%; BACKGROUND-COLOR: #d7e4ef; TEXT-ALIGN: center" scope="col">Düzenle</th> <th style="WIDTH: 20%; BACKGROUND-COLOR: #d7e4ef; TEXT-ALIGN: center" scope="col">Sil</th> </tr> </tbody> <tbody> @foreach (var item in @Model) { <tr> <td style="WIDTH: 20%; TEXT-ALIGN: center">@item.Name</td> <td style="WIDTH: 20%; TEXT-ALIGN: center">@item.Description</td> <td style="WIDTH: 20%; TEXT-ALIGN: center"><img id="theImg" src="../Images/@item.ImageUrl" width="30" height="30" /></td> <td style="WIDTH: 20%; TEXT-ALIGN: center">@item.Price</td> <td style="WIDTH: 20%; TEXT-ALIGN: center"><input type="button" onclick="editProduct(@item.ID)" value="Detay"/></td> <td style="WIDTH: 20%; TEXT-ALIGN: center"><input type="button" onclick="deleteProduct(@item.ID)" value="Sil" /></td> </tr> } </tbody> </table><br /> |
HomeController/ProductList[Get]:
1 2 3 4 5 6 7 8 9 |
public PartialViewResult ProductList() { List<DAL.tblProduct> data; using (JewelleryStoreDB dbContext = new JewelleryStoreDB()) { data = dbContext.tblProduct.ToList(); } return PartialView(data); } |
Views/Home/Admin.cshtml/editProduct() & deleteProduct() functions:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 |
function deleteProduct(productID) { var result = confirm("Kayıdı silmek istediğinize eminmisiniz?"); if (result == true) { $.post("/Home/ProductDelete", { 'DetailID': productID }, function (listView) { $("#productList").html(listView); messagehub.server.refreshProduct(); }); } } function editProduct(productID) { $.post("/Home/ProductDetail", { 'DetailID': productID }, function (detailView) { $("#productDetail").html(detailView); $('#status').html(""); $('#status').prepend('<img id="theImg" src="../Images/' + $('#ImageUrl').val() + '" width="100" height="100"/>'); $("#btnSubmit").attr('value', 'Güncelle'); }); } |
HomeControl/ ProductDelete[Post] & ProductDetial[Post] :
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 |
[HttpPost] public PartialViewResult ProductDetail(int DetailID) { tblProduct data; using (JewelleryStoreDB dbContext = new JewelleryStoreDB()) { data = dbContext.tblProduct.FirstOrDefault(pro => pro.ID == DetailID); } return PartialView("ProductDetail", data); } [HttpPost] [LogAttribute(LogType.ProductDelete,false)] public PartialViewResult ProductDelete(int DetailID) { using (JewelleryStoreDB dbContext = new JewelleryStoreDB()) { Session["ProductID"] = DetailID; tblProduct product = dbContext.tblProduct.FirstOrDefault(pro => pro.ID == DetailID); dbContext.tblProduct.Remove(product); dbContext.SaveChanges(); var data = dbContext.tblProduct.ToList(); return PartialView("ProductList", data); } } |
Yapılan değişikliklerin client tarafına yansıtılması için dikkat ederseniz Admin ekranındaki delete ve save functionlarında aşağıdaki refreshProduct() function’ı çağrılmıştır.
messagehub.server.refreshProduct();
View/Admin.cshtml’de signalR için alttaki script’in eklenmesi gerekmektedir
1 2 3 4 5 6 |
<script src="@Url.Content("~/Scripts/jquery.signalR-2.1.1.min.js")" type="text/javascript"></script> <script src="@Url.Content("~/signalr/hubs")"></script> <script> var messagehub = $.connection.jewellery; $.connection.hub.start(); </script> |
Server tarafındaki HomeController altındaki Jewellery :Hub classımız aşadaki gibi tanımlanmıştır.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 |
public class Jewellery : Hub { public void RefreshProduct() { List<DAL.tblProduct> data; using (JewelleryStoreDB dbContext = new JewelleryStoreDB()) { data = dbContext.tblProduct.ToList(); } string viewName = @"~/Views/Shared/ProductScreen.cshtml"; var productScreenPrint = Helper.GetRazorViewAsString(data, viewName); Clients.All.reloadProduct(productScreenPrint); } } |
Yukarıdaki RefreshProduct’a dikkat ederseniz, ürünlerde değişiklik olunca ProductScreen, ilgili datamodel ile doldurulup, tüm clientlardaki reloadProduct function’una parametre olarak gönderilmektedir. Buradaki önemli nokta bu class’ın controller’dan türemediği için result olarak PartialView döndürememesidir. Bu nedenle PartialView’umuzu string’e çeviren bir helper yazdık. Böylece ProductScreen view’umuzu ilgili model ile doldurup string’e çevrilecek. Client tarafında da Index.cshtml’de ilgili div’in altına (<div id=”productScreen”></div>) bu html basılacak.
Model/Helper.cs: İlgili View’ı string’e çevirir.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 |
using JewelleryStore.Controllers; using System.IO; using System.Web; using System.Web.Mvc; using System.Web.Routing; namespace JewelleryStore.Models { public class Helper { public static string GetRazorViewAsString(object model, string filePath) { var st = new StringWriter(); var context = new HttpContextWrapper(HttpContext.Current); var routeData = new RouteData(); var controllerContext = new ControllerContext(new RequestContext(context, routeData), new HomeController()); var razor = new RazorView(controllerContext, filePath, null, false, null); razor.Render(new ViewContext(controllerContext, razor, new ViewDataDictionary(model), new TempDataDictionary(), st), st); return st.ToString(); } } } |
View/Home/Index.cshtml: Ürünlerin client’lara gösterildiği ana ekran.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 |
@model List<DAL.tblProduct> @{ ViewBag.Title = "Index"; } <script src="@Url.Content("~/Scripts/jquery.signalR-2.1.1.min.js")" type="text/javascript"></script> <script src="@Url.Content("~/signalr/hubs")"></script> <script> var messagehub = $.connection.jewellery; messagehub.client.reloadProduct = function (data) { $("#productScreen").html(data); } $.connection.hub.start(); </script> <link href='http://fonts.googleapis.com/css?family=Lobster' rel='stylesheet' type='text/css'> <link href='http://fonts.googleapis.com/css?family=Dancing+Script' rel='stylesheet' type='text/css'> <link href='http://fonts.googleapis.com/css?family=Paytone+One' rel='stylesheet' type='text/css'> <img src="~/Images/main_header.jpg" height="170px" width="960px"/><br /><br /> <style> .left-panel { background-color: #ccc; width: 27%; height: 300px; float: left; } .center-panel { background-color: Gray; width: 27%; height: 300px; float: left; margin-left:20px; } .right-panel { background-color: lightgrey; width: 27%; height: 300px; float: left; margin-left:20px; } </style> <body background="/Images/orta-desen.png"> <div id="productScreen"> @{Html.RenderPartial("ProductScreen", Model);} </div> </body> |
Yukarıdaki kod’a dikkat ederseniz server side’dan çağrılan messagehub.client.reloadProduct succeed durumunda ilgili productScreen divini tekardan doldurmaktadır.
Views/Shared/ProductScreen: Ürünlerin client tarafında gösterildiği Partial View’dur.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 |
@model List<DAL.tblProduct> @{int rowCount = 0;} @foreach (var item in Model) { rowCount++; if (rowCount > 3) { <div style="clear: both;"></div> <br /><br /> rowCount = 1; } if (rowCount == 1) { <div class="left-panel"> <div style="text-align:center; font-family: 'Lobster', cursive; font-size:x-large; color:white">@item.Name</div> <div style="clear: both;"></div> <table cellpadding="15"> <tr> <td> <img src="~/Images/@item.ImageUrl" width="150" height="150" /> </td> <td style="font-family: 'Dancing Script', cursive; font-size:larger;"><b>@item.Description</b></td> </tr> <tr><td align="center" style="font-family: 'Paytone One', sans-serif; font-size:x-large; color:#0B3861">@Math.Round((double)item.Price, 2) TL</td></tr> </table> </div> } else if (rowCount == 2) { <div class="center-panel"> <div style="text-align:center; font-family: 'Lobster', cursive; font-size:x-large; color:white">@item.Name</div> <div style="clear: both;"></div> <table cellpadding="15"> <tr> <td> <img src="~/Images/@item.ImageUrl" width="150" height="150" /> </td> <td style="font-family: 'Dancing Script', cursive; font-size:larger;"><b>@item.Description</b></td> </tr> <tr><td align="center" style="font-family: 'Paytone One', sans-serif; font-size:x-large; color:#0B3861">@Math.Round((double)item.Price, 2) TL</td></tr> </table> </div> } else if (rowCount == 3) { <div class="right-panel"> <div style="text-align:center; font-family: 'Lobster', cursive; font-size:x-large; color:white">@item.Name</div> <div style="clear: both;"></div> <table cellpadding="15"> <tr> <td> <img src="~/Images/@item.ImageUrl" width="150" height="150" /> </td> <td style="font-family: 'Dancing Script', cursive; font-size:larger;"><b>@item.Description</b></td> </tr> <tr><td align="center" style="font-family: 'Paytone One', sans-serif; font-size:x-large; color:#0B3861">@Math.Round((double)item.Price, 2) TL</td></tr> </table> </div> } } <div style="clear: both;"></div> <br /> |
HomeController.cs’in tamamı:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 |
using System.Data; using DAL; using JewelleryStore.Models; using System; using System.Collections.Generic; using System.Linq; using System.Net; using System.Net.Mail; using System.Web; using System.Web.Mvc; using System.IO; using Microsoft.AspNet.SignalR; namespace JewelleryStore.Controllers { public class HomeController : Controller { // GET: Home [LogAttribute(LogType.Home,false)] public ActionResult Index() { if (Session["UserID"] == null) { return RedirectToAction("Login"); } ViewBag.Title = "Index"; using (JewelleryStoreDB dbContext = new JewelleryStoreDB()) { var data = dbContext.tblProduct.ToList(); return View(data); } } [HttpPost] public bool SendConfirmMail(string email) { try { string Guid = string.Empty; using (JewelleryStoreDB dbContext = new JewelleryStoreDB()) { Guid = dbContext.tblUser.FirstOrDefault(us => us.Email == email).GuidID.ToString(); } SmtpClient sc = new SmtpClient(); sc.Port = 587; sc.Host = "smtp.gmail.com"; sc.EnableSsl = true; sc.Credentials = new NetworkCredential("Username", "Password"); MailMessage mail = new MailMessage(); mail.From = new MailAddress("JewelleryStore78@gmail.com", "Jewellery Store"); mail.To.Add(email); mail.Subject = "JewelleryStore Login Confirm Link"; mail.IsBodyHtml = true; mail.Body = "<a href='http://localhost:17716/ConfirmJewelleryLogin/" + Guid + "' TARGET = '_blank'>Please Confirm Your Mail!</a>"; //mail.Subject = "JewelleryStore Login Confirm Link"; mail.IsBodyHtml = true; mail.Body = "<a href='jewellerystores.azurewebsites.net/ConfirmJewelleryLogin/" + Guid + "' TARGET = '_blank'>Please Confirm Your Mail!</a>"; sc.Send(mail); return true; } catch (Exception ex) { return false; } } public void SendConfirmMail(string Guid, string email) { try { SmtpClient sc = new SmtpClient(); sc.Port = 587; sc.Host = "smtp.gmail.com"; sc.EnableSsl = true; sc.Credentials = new NetworkCredential("JewelleryStore78@gmail.com", "Sahibinden78"); MailMessage mail = new MailMessage(); mail.From = new MailAddress("JewelleryStore78@gmail.com", "Jewellery Store"); mail.To.Add(email); mail.Subject = "JewelleryStore Login Confirm Link"; mail.IsBodyHtml = true; mail.Body = "<a href='http://localhost:17716/ConfirmJewelleryLogin/" + Guid + "' TARGET = '_blank'>Please Confirm Your Mail!</a>"; //mail.Subject = "JewelleryStore Login Confirm Link"; mail.IsBodyHtml = true; mail.Body = "<a href='jewellerystores.azurewebsites.net/ConfirmJewelleryLogin/" + Guid + "' TARGET = '_blank'>Please Confirm Your Mail!</a>"; sc.Send(mail); } catch (Exception ex) { } } [HttpGet] public ActionResult Login() { HttpCookie userCookie = Request.Cookies["IsRemmber"]; if (userCookie != null) { ViewBag.Email = userCookie.Value; } ViewBag.Title = "Login"; return View(); } [HttpPost] [LogAttribute(LogType.LogIn,false)] public int Login(User user) { //Cookie İşlemleri if (user.IsRemmber) { HttpCookie userCookie = new HttpCookie("IsRemmber"); userCookie.Value = user.Email; userCookie.Expires = DateTime.Now.AddDays(1d); Response.Cookies.Add(userCookie); } //Bitti-------------- using (JewelleryStoreDB dbContext = new JewelleryStoreDB()) { var usr = dbContext.tblUser.FirstOrDefault(us => us.Email == user.Email && us.Password == user.Password); if (usr == null || usr.isChecked == false) { if (usr != null && usr.isChecked == false) { return (int)LoginState.WaitForApprove;//Kayıt var Onaylanmamış } else if (dbContext.tblUser.FirstOrDefault(us => us.Email == user.Email) != null) { if (dbContext.tblUser.FirstOrDefault(us => us.Email == user.Email).isChecked == false) { return (int)LoginState.WaitForApproveWrongPassword;//Şifre Yanlış Onaylanmamış Mail; } return (int)LoginState.WrongPassword;//Şifre yanlış } else { return (int)LoginState.NoRecord;//Kayıt yok } } else { Session["UserID"] = usr.ID; } } return 2;//Kayıtlı } [HttpGet] public ActionResult SignIn(string Password, string Email) { tblUser user = new tblUser() { Password = Password, Email = Email }; return View(user); } [HttpPost] [LogAttribute(LogType.WaitForConfirm,false)] public int SignIn(tblUser user) { try { Guid _Guid = System.Guid.NewGuid(); user.GuidID = _Guid; user.isChecked = false; SendConfirmMail(_Guid.ToString(), user.Email); using (JewelleryStoreDB dbContext = new JewelleryStoreDB()) { if (dbContext.tblUser.FirstOrDefault(us => us.Email == user.Email) != null) { return 3; } dbContext.tblUser.Add(user); dbContext.SaveChanges(); } return 1; } catch (Exception) { return 2; } } [LogAttribute(LogType.SignIn,false)] public ActionResult ConfirmJewelleryLogin(Guid guid) { using (JewelleryStoreDB dbContext = new JewelleryStoreDB()) { var user = dbContext.tblUser.First(us => us.GuidID == guid); user.isChecked = true; dbContext.SaveChanges(); Session["UserID"] = user.ID; } return RedirectToAction("Admin"); } [LogAttribute(LogType.LogOut,true)] public ActionResult LogOut() { Session.Remove("UserID"); return RedirectToAction("Login"); } [LogAttribute(LogType.Admin,false)] public ActionResult Admin() { if (Session["UserID"] == null) { return RedirectToAction("Login"); } List<DAL.tblProduct> data; using (JewelleryStoreDB dbContext = new JewelleryStoreDB()) { data = dbContext.tblProduct.ToList(); } ViewBag.Title = "Admin"; return View(data); } [HttpPost] [LogAttribute(LogType.ProductInsert,false)] public int Admin(tblProduct product) { try { using (JewelleryStoreDB dbContext = new JewelleryStoreDB()) { dbContext.tblProduct.Add(product); product.CreatedDate = DateTime.Now; dbContext.SaveChanges(); Session["ProductID"] = product.ID; } return 1; } catch { return 2; } } [LogAttribute(LogType.ProductUpdate,false)] public int AdminUpdate(tblProduct product) { try { using (JewelleryStoreDB dbContext = new JewelleryStoreDB()) { tblProduct tp = dbContext.tblProduct.FirstOrDefault(t => t.ID == product.ID); tp.ImageUrl = product.ImageUrl; tp.Name = product.Name; tp.Price = product.Price; tp.Description = product.Description; dbContext.SaveChanges(); Session["ProductID"] = product.ID; } return 1; } catch { return 2; } } [HttpPost] [ValidateAntiForgeryToken] public string FileUpload(IEnumerable<HttpPostedFileBase> files) { string fileName = string.Empty; if (files != null) { foreach (var file in files) { if (file != null && file.ContentLength > 0) { fileName = Path.GetFileName(file.FileName); var path = Path.Combine(Server.MapPath("~/Images"), fileName); file.SaveAs(path); } } } return fileName; } public PartialViewResult ProductList() { List<DAL.tblProduct> data; using (JewelleryStoreDB dbContext = new JewelleryStoreDB()) { data = dbContext.tblProduct.ToList(); } return PartialView(data); } public PartialViewResult ProductDetail() { return PartialView("ProductDetail", new tblProduct()); } [HttpPost] public PartialViewResult ProductDetail(int DetailID) { tblProduct data; using (JewelleryStoreDB dbContext = new JewelleryStoreDB()) { data = dbContext.tblProduct.FirstOrDefault(pro => pro.ID == DetailID); } return PartialView("ProductDetail", data); } [HttpPost] [LogAttribute(LogType.ProductDelete,false)] public PartialViewResult ProductDelete(int DetailID) { using (JewelleryStoreDB dbContext = new JewelleryStoreDB()) { Session["ProductID"] = DetailID; tblProduct product = dbContext.tblProduct.FirstOrDefault(pro => pro.ID == DetailID); dbContext.tblProduct.Remove(product); dbContext.SaveChanges(); var data = dbContext.tblProduct.ToList(); return PartialView("ProductList", data); } } [LogAttribute(LogType.Log,true)] public ActionResult Log() { if (Session["UserID"] == null) { return RedirectToAction("Login"); } ViewBag.Title = "Log"; List<DAL.tblLog> data; List<Log> LogData = new List<Log>(); using (JewelleryStoreDB dbContext = new JewelleryStoreDB()) { data = dbContext.tblLog.OrderByDescending(tg=>tg.ID).ToList(); foreach (var item in data) { Log lg = new Log(); lg.ID = item.ID; lg.LogType = item.LogType; var product = dbContext.tblProduct.FirstOrDefault(tp => tp.ID == item.ProductID); var user = dbContext.tblUser.FirstOrDefault(us => us.ID == item.UserID); string prdoct=item.ProductID==null?"-":item.ProductID.ToString(); lg.ProductName = product == null ? prdoct : product.Name; lg.UserName = user == null ? item.UserID.ToString() : user.Name; lg.CreatedDate = item.CreatedDate; LogData.Add(lg); } } return View(LogData); } public class Jewellery : Hub { public void RefreshProduct() { List<DAL.tblProduct> data; using (JewelleryStoreDB dbContext = new JewelleryStoreDB()) { data = dbContext.tblProduct.ToList(); } string viewName = @"~/Views/Shared/ProductScreen.cshtml"; var productScreenPrint = Helper.GetRazorViewAsString(data, viewName); Clients.All.reloadProduct(productScreenPrint); } } } } |
Views/Home/Admin.cshtml’in tamamı:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 |
@using DAL @model List<DAL.tblProduct> @{ ViewBag.Title = "Admin"; } <link href="/Content/signin.css" rel="stylesheet"> <script src="@Url.Content("~/Scripts/jquery.signalR-2.1.1.min.js")" type="text/javascript"></script> <script src="@Url.Content("~/signalr/hubs")"></script> <script> var messagehub = $.connection.jewellery; $.connection.hub.start(); </script> <script> function deleteProduct(productID) { var result = confirm("Kayıdı silmek istediğinize eminmisiniz?"); if (result == true) { $.post("/Home/ProductDelete", { 'DetailID': productID }, function (listView) { $("#productList").html(listView); messagehub.server.refreshProduct(); }); } } function editProduct(productID) { $.post("/Home/ProductDetail", { 'DetailID': productID }, function (detailView) { $("#productDetail").html(detailView); $('#status').html(""); $('#status').prepend('<img id="theImg" src="../Images/' + $('#ImageUrl').val() + '" width="100" height="100"/>'); $("#btnSubmit").attr('value', 'Güncelle'); }); } function saveProduct(ProductID) { if ($("#btnSubmit").attr('value') == 'Kaydet') { $.post("/Home/Admin", { 'Name': $("#Name").val(), 'ImageUrl': $("#ImageUrl").val(), 'Price': $("#Price").val(), 'Description': $("#Description").val() }, function (isOK) { if (isOK == 1) { $.get("/Home/ProductList", function (listView) { $("#productList").html(listView); messagehub.server.refreshProduct(); }); $.get("/Home/ProductDetail", function (detailView) { $("#productDetail").html(detailView); }); $("#fileUploadControl").val(""); $('#status').html(""); } }); } else { $.post("/Home/AdminUpdate", { 'ID': ProductID, 'Name': $("#Name").val(), 'ImageUrl': $("#ImageUrl").val(), 'Price': $("#Price").val(), 'Description': $("#Description").val() }, function (isOK) { if (isOK == 1) { $.get("/Home/ProductList", function (listView) { $("#productList").html(listView); messagehub.server.refreshProduct(); }); $.get("/Home/ProductDetail", function (detailView) { $("#productDetail").html(detailView); }); $("#fileUploadControl").val(""); $('#status').html(""); } }); } } </script> <h2>Jewellery Store ®</h2> <div class="container"> <div id="fileUpload"> @{Html.RenderPartial("FileUpload");} </div><br /> <div id="productDetail"> @{Html.RenderPartial("ProductDetail", new tblProduct());} </div><br /> <div id="productList"> @{Html.RenderPartial("ProductList", Model);} </div> </div> |
Örnek Url(İptal) : http://jewellerystores.azurewebsites.net/Home/Login
Source Code: http://www.borakasmer.com/projects/JewelleryStore.rar
Böylece bir kuyumcu online mazasında yeni bir ürün girilmesi, silinmesi ve düzeltilmesi durumunda signalR ile client’ları bu değişimden haberdar ettik. Partial View’ımızı html string’e çevirdik. Ajax post ile image upload yaptık. Ayrıca Admin sayfamızda görüldüğü gibi farklı partial viewlar ile nasıl çalışabileceğimizi gördük.Partial viewlarda çağrılan java script kodlarını kondukları ana sayfa olan Admin sayfasına koyulmasındaki amacın, çağrılma ve yükleme anında erişim problemini ortadan kaldırmak olduğunu gördük.
Geldik bir makalenin daha sonuna yeni bir makalede görüşmek üzere hoşçakalın.
Son Yorumlar