WCF服务从SQL数据库

时间:2016-06-21 18:58:42

标签: c# asp.net asp.net-mvc asp.net-mvc-4

我正在尝试在.NET中构建一个Web服务,它将与SQL数据库进行交互。此Web服务稍后将由MVC使用,其中将显示此数据并与之交互。

我已准备好数据库,数据库和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")
}

1 个答案:

答案 0 :(得分: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>
}