2016-06-21 69 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