2016-06-21 66 views
0

我想在.NET中構建一個Web服務,它將與SQL數據庫交互。此Web服務稍後將由MVC消耗,在該MVC中將顯示該數據並與之交互。WCF服務讀取,寫入,編輯,從SQL數據庫刪除數據

我已準備好數據庫,數據庫和Web服務之間的連接已經完成,我已將我的MVC項目添加到我的解決方案中。我有我的創建,讀取和更新功能工作,但刪除拒絕工作。

當單擊刪除鏈接時,它會顯示我的記錄,要求我確認刪除,並且當我單擊是時,它不起作用/刪除。請幫忙。

這是我Service.cs文件

using System; 
using System.Collections.Generic; 
using System.Linq; 
using System.Runtime.Serialization; 
using System.ServiceModel; 
using System.ServiceModel.Web; 
using System.Text; 

// NOTE: You can use the "Rename" command on the "Refactor" menu to change the class name "Service" in code, svc and config file together. 
public class Service : IService 
{ 
    public List<Student> GetStudent() 
    { 
     var objContext = new ContosoUniversityDataEntities(); 
     var students = objContext.Students; 

     return students.ToList<Student>(); 
    } 

    public string InsertStudent(string firstName, string lastName, string middleName) 
    { 
     try 
     { 
      var objContext = new ContosoUniversityDataEntities(); 

      Student s = new Student() 
      { 
       FirstName = firstName, 
       LastName = lastName, 
       MiddleName = middleName, 
       EnrollmentDate = DateTime.Now 
      }; 

      objContext.Students.Add(s); 
      objContext.SaveChanges(); 

      return "Success"; 
     } 
     catch { return "failure"; } 
    } 
    public string Update(int id, string firstName, string middleName, string lastName) 
    { 
     try 
     { 
      var objContext = new ContosoUniversityDataEntities(); 
      var s = (from d in objContext.Students where d.StudentID == id select d).Single(); 
      s.FirstName = firstName; 
      s.MiddleName = middleName; 
      s.LastName = lastName; 

      objContext.SaveChanges(); 
      return "Success"; 
     } 
     catch { return "failure"; } 

    } 
    public string Delete(int id) 
    { 
     try 
     { 
      var objContext = new ContosoUniversityDataEntities(); 
      var s = (from d in objContext.Students where d.StudentID == id select d); 

      foreach(var y in s) 
      { 
       objContext.Students.Remove(y); 
      } 

      objContext.SaveChanges(); 
      return "Success"; 
     } 
     catch { return "failure"; } 
    } 




    public List<Student> InsertStudent() 
    { 
     throw new NotImplementedException(); 
    } 


    public string Update(string firstName, string lastName, string middleName) 
    { 
     throw new NotImplementedException(); 
    } 
} 

這是我DeleteController類

using MvcWcfApplication.Models; 
using System; 
using System.Collections.Generic; 
using System.Linq; 
using System.Web; 
using System.Web.Mvc; 

namespace MvcWcfApplication.Controllers 
{ 
    public class DeleteController : Controller 
    { 
     // 
     // GET: /Delete/ 

     [HttpGet] 
     public ActionResult Delete(int id) 
     { 
      ServiceReference1.ServiceClient obj = new ServiceReference1.ServiceClient(); 

      var students = obj.GetStudent(); 
      var std = students.Where(s => s.StudentID == id).FirstOrDefault(); 
      return View(std); 
     } 

     [HttpPost] 
     public ActionResult Delete(Studentdata mb) 
     { 
      if (ModelState.IsValid) //checking model is valid or not 
      { 
       ServiceReference1.ServiceClient obj = new ServiceReference1.ServiceClient(); 

       string message = obj.Delete(mb.StudentID); 
       if (message == "Success") 
       { 
        ViewData["result"] = message; 
        ModelState.Clear(); //clearing model 
        return View(); 
       } 
       else 
       { 
        ModelState.AddModelError("", "We are currently down"); 
        return View(); 
       } 


      } 
      else 
      { 
       ModelState.AddModelError("", "Error in saving data"); 
       return View(); 
      } 
     } 

    } 
} 

這是Delete.cshtml

@model MvcWcfApplication.ServiceReference1.Student 

@{ 
    ViewBag.Title = "Delete"; 
} 

@{ 
    if (ViewData["result"] != "" && ViewData["result"] != null) 
    { 
     ViewData["result"] = null; 
     <script type="text/javascript" language="javascript"> 
      alert("Data deleted Successfully"); 
     </script> 
    } 
} 

<h2>Delete</h2> 

<h3>Are you sure you want to delete this?</h3> 
<fieldset> 
    <legend>Student</legend> 

    <div class="display-label"> 
     @Html.DisplayNameFor(model => model.EnrollmentDate) 
    </div> 
    <div class="display-field"> 
     @Html.DisplayFor(model => model.EnrollmentDate) 
    </div> 

    <div class="display-label"> 
     @Html.DisplayNameFor(model => model.FirstName) 
    </div> 
    <div class="display-field"> 
     @Html.DisplayFor(model => model.FirstName) 
    </div> 

    <div class="display-label"> 
     @Html.DisplayNameFor(model => model.LastName) 
    </div> 
    <div class="display-field"> 
     @Html.DisplayFor(model => model.LastName) 
    </div> 

    <div class="display-label"> 
     @Html.DisplayNameFor(model => model.MiddleName) 
    </div> 
    <div class="display-field"> 
     @Html.DisplayFor(model => model.MiddleName) 
    </div> 
</fieldset> 
@using (Html.BeginForm()) { 

    @Html.AntiForgeryToken() 
    <p> 
     <input id="Submit" onclick="return confirm('Are you sure you want delete');" type="submit" 
       value="Delete" /> | 
     @Html.ActionLink("Back to List", "Index", "Db") 
    </p> 
} 

這是UpdateController類

using MvcWcfApplication.Models; 
using System; 
using System.Collections.Generic; 
using System.Linq; 
using System.Web; 
using System.Web.Mvc; 

namespace MvcWcfApplication.Controllers 
{ 
    public class UpdateController : Controller 
    { 
     // 
     // GET: /Update/ 

     [HttpGet] 
     public ActionResult Update(int id) 
     { 
      ServiceReference1.ServiceClient obj = new ServiceReference1.ServiceClient(); 

      var students = obj.GetStudent(); 
      var std = students.Where(s => s.StudentID == id).FirstOrDefault(); 
      return View(std); 
     } 

     [HttpPost] 
     public ActionResult Update(Studentdata MB) 
     { 
      if (ModelState.IsValid) //checking model is valid or not 
      { 
       ServiceReference1.ServiceClient obj = new ServiceReference1.ServiceClient(); 

       string message = obj.Update(MB.StudentID, MB.FirstName, MB.LastName, MB.MiddleName); 
       if (message == "Success") 
       { 
        ViewData["result"] = message; 
        ModelState.Clear(); //clearing model 
        return View(); 
       } 
       else 
       { 
        ModelState.AddModelError("", "We are currently down"); 
        return View(); 
       } 


      } 
      else 
      { 
       ModelState.AddModelError("", "Error in saving data"); 
       return View(); 
      } 
     } 

    } 
} 

這是我Update.cshtml

@model MvcWcfApplication.ServiceReference1.Student 

@{ 
    ViewBag.Title = "Update"; 
} 

@{ 
    if (ViewData["resultUpdate"] != "" && ViewData["resultUpdate"] != null) 
    { 
     ViewData["resultUpdate"] = null; 
     <script type="text/javascript" language="javascript"> 
      alert("Data updated Successfully"); 
     </script> 
    } 
} 

<h2>Update</h2> 

@using (Html.BeginForm()) { 
    @Html.AntiForgeryToken() 
    @Html.ValidationSummary(true) 

    <fieldset> 
     <legend>Student</legend> 



     <div class="editor-label"> 
      @Html.LabelFor(model => model.FirstName) 
     </div> 
     <div class="editor-field"> 
      @Html.EditorFor(model => model.FirstName) 
      @Html.ValidationMessageFor(model => model.FirstName) 
     </div> 

     <div class="editor-label"> 
      @Html.LabelFor(model => model.LastName) 
     </div> 
     <div class="editor-field"> 
      @Html.EditorFor(model => model.LastName) 
      @Html.ValidationMessageFor(model => model.LastName) 
     </div> 

     <div class="editor-label"> 
      @Html.LabelFor(model => model.MiddleName) 
     </div> 
     <div class="editor-field"> 
      @Html.EditorFor(model => model.MiddleName) 
      @Html.ValidationMessageFor(model => model.MiddleName) 
     </div> 

     @Html.HiddenFor(model => model.StudentID) 

     <p> 
      <input type="submit" value="Save" /> 
     </p> 
    </fieldset> 
} 

<div> 
    @Html.ActionLink("Back to List", "Index") 
</div> 

@section Scripts { 
    @Scripts.Render("~/bundles/jqueryval") 
} 
+0

好開始鑄造異常的'Delete'方法將變量:catch(Exception ex){}'並找出問題所在。 – pay

回答

0

您提交沒有值的空形式把ID作爲隱藏字段

@model MvcWcfApplication.ServiceReference1.Student 

@{ 
    ViewBag.Title = "Delete"; 
} 

@{ 
    if (ViewData["result"] != "" && ViewData["result"] != null) 
    { 
     ViewData["result"] = null; 
     <script type="text/javascript" language="javascript"> 
      alert("Data deleted Successfully"); 
     </script> 
    } 
} 

<h2>Delete</h2> 

<h3>Are you sure you want to delete this?</h3> 
<fieldset> 
    <legend>Student</legend> 

    <div class="display-label"> 
     @Html.DisplayNameFor(model => model.EnrollmentDate) 
    </div> 
    <div class="display-field"> 
     @Html.DisplayFor(model => model.EnrollmentDate) 
    </div> 

    <div class="display-label"> 
     @Html.DisplayNameFor(model => model.FirstName) 
    </div> 
    <div class="display-field"> 
     @Html.DisplayFor(model => model.FirstName) 
    </div> 

    <div class="display-label"> 
     @Html.DisplayNameFor(model => model.LastName) 
    </div> 
    <div class="display-field"> 
     @Html.DisplayFor(model => model.LastName) 
    </div> 

    <div class="display-label"> 
     @Html.DisplayNameFor(model => model.MiddleName) 
    </div> 
    <div class="display-field"> 
     @Html.DisplayFor(model => model.MiddleName) 
    </div> 
</fieldset> 
@using (Html.BeginForm()) { 

    @Html.AntiForgeryToken() 
    @Html.HiddenFor(model => model.StudentID) 
    <p> 
     <input id="Submit" onclick="return confirm('Are you sure you want delete');" type="submit" 
       value="Delete" /> | 
     @Html.ActionLink("Back to List", "Index", "Db") 
    </p> 
} 
+0

嗨,我試過了,它不起作用。 – Ollivander

+0

然後,原因將是您的Model.IsValid,因爲除了您的模型中的studentID以外的所有內容都是null或默認值。如果您有任何必需的屬性,模型將變爲無效。檢查是否輸入if也看看你是否在控制器端看到StudentID。 – Krishna

+0

它的工作!謝謝。爲什麼必需屬性阻止記錄被刪除? – Ollivander