从不同的表中获取数据并在asp.net mvc5中显示为1个联接表

时间:2018-07-03 08:34:57

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

我已经为数据库中的单个表(例如电影数据库)开发了CRUD应用程序。我想通过sql查询将不同表的指定列显示出来。并且在插入或编辑选项时,所有表都必须自动更新。

namespace AnimeshDB.Models
{
using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;

public partial class Animesh
{
    public int ID { get; set; }
    [Required(ErrorMessage = "this feild is required")]
    public string Name { get; set; }
    [Required(ErrorMessage = "this feild is required")]
    public int Year { get; set; }
    public string Plot { get; set; }
    public string Poster { get; set; }
}
}

这是我的观点。

@model AnimeshDB.Models.Animesh
@{
Layout = null;
}
@using (Html.BeginForm("AddOrEdit", "Movie", FormMethod.Post, new { onsubmit = "return SubmitForm(this)" }))
{
@Html.HiddenFor(model => model.ID)
@*<div class="form-group">
    @Html.LabelFor(model => model.ID, new { @class="control-label"})
    @Html.EditorFor(model => model.ID, new {htmlAttributes= new { @class="form-control" } })

</div>*@
<div class="form-group">
    @Html.LabelFor(model => model.Name, new { @class = "control-label" })
    @Html.EditorFor(model => model.Name, new { htmlAttributes = new { @class = "form-control" } })
    @Html.ValidationMessageFor(model => model.Name)
</div>
<div class="form-group">
    @Html.LabelFor(model => model.Year, new { @class = "control-label" })
    @Html.EditorFor(model => model.Year, new { htmlAttributes = new { @class = "form-control" } })
    @Html.ValidationMessageFor(model => model.Year)
</div>
<div class="form-group">
    @Html.LabelFor(model => model.Plot, new { @class = "control-label" })
    @Html.EditorFor(model => model.Plot, new { htmlAttributes = new { @class = "form-control" } })


</div>
<div class="form-group">
    @Html.LabelFor(model => model.Poster, new { @class = "control-label" })
    @Html.EditorFor(model => model.Poster, new { htmlAttributes = new { @class = "form-control" } })

</div>

<div class="form-group">
    <input type="submit" value="Submit" class="btn btn-primary" />
    <input type="reset" value="Reset" class="btn" />

</div>}

这是我的控制器

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using AnimeshDB.Models;
using System.Data.Entity.Validation;
using System.Data.Entity;

namespace AnimeshDB.Controllers
{
public class MovieController : Controller
{
    // GET: Movie
    public ActionResult Index()
    {
        return View();
    }

    public ActionResult GetData()
    {
        using (DBModel db = new DBModel())
        {
            List<Animesh> movList = db.Animeshes.ToList<Animesh>();
            return Json(new { data = movList }, JsonRequestBehavior.AllowGet);
        }
    }

    [HttpGet]
    public ActionResult AddOrEdit(int id = 0)
    {
        if (id == 0) 
             return View(new Animesh());
        else
        {
            using (DBModel db = new DBModel())
            {
                return View(db.Animeshes.Where(x => x.ID == id).FirstOrDefault<Animesh>());
            }

        }
    }

    [HttpPost]
    public ActionResult AddOrEdit(Animesh mov)
    {
        using (DBModel db = new DBModel())
        {
            try
            {
                if (mov.ID == 0)
                {
                    db.Animeshes.Add(mov);
                    db.SaveChanges();
                    return Json(new { success = true, message = "Saved Successfully!!" }, JsonRequestBehavior.AllowGet);
                }
                else
                {
                    db.Entry(mov).State = EntityState.Modified;
                    db.SaveChanges();
                    return Json(new { success = true, message = "Updated Successfully!!" }, JsonRequestBehavior.AllowGet);
                }
            }
            catch (DbEntityValidationException e)
            {
                foreach (var eve in e.EntityValidationErrors)
                {
                    Console.WriteLine("Entity of type \"{0}\" in state \"{1}\" has the following validation errors:",
                        eve.Entry.Entity.GetType().Name, eve.Entry.State);
                    foreach (var ve in eve.ValidationErrors)
                    {
                        Console.WriteLine("- Property: \"{0}\", Error: \"{1}\"",
                            ve.PropertyName, ve.ErrorMessage);
                    }
                }
                throw;
            }
        }

    }
    [HttpPost]
    public ActionResult Delete(int id)
    {
        using (DBModel db = new DBModel())
        {
            Animesh mov = db.Animeshes.Where(x => x.ID == id).FirstOrDefault<Animesh>();
            db.Animeshes.Remove(mov);
            db.SaveChanges();
            return Json(new { success = true, message = "Deleted Successfully!!" }, JsonRequestBehavior.AllowGet);
        }
    }

}}

最后,这是我的Index.cshtml文件代码

@{
ViewBag.Title = "Movie List";
 }


<h2>Movie CRUD Operations</h2>

<a class="btn btn-success" style="margin-bottom:10px" onclick="PopupForm('@Url.Action("AddOrEdit","Movie")')"><i class="fa fa-plus"></i> Add New</a>


<table id="movieTable" class="table table-striped table-bordered" style="width:100%">
<thead>
    <tr>
        <th>Name</th>
        <th>Year</th>
        <th>Plot</th>
        <th>Poster</th>
        <th></th>
    </tr>
</thead>

                   @section脚本     {

<script>
    var Popup, dataTable;
    $(document).ready(function () {
        dataTable = $("#movieTable").DataTable({
            "ajax": {
                "url": "/Movie/GetData",
                "type": "GET",
                "datatype": "json"
            },
            "columns": [
                { "data": "Name" },
                { "data": "Year" },
                { "data": "Plot" },
                { "data": "Poster" },
                {
                    "data": "ID", "render": function (data) {
                        return "<a class='btn btn-default btn-sm' onclick=PopupForm('@Url.Action("AddOrEdit","Movie")/"+ data +"')><i class='fa fa-pencil'></i> Edit</a><a class='btn btn-danger btn-sm' style='margin-left:14px' onclick=Delete("+ data +")><i class='fa fa-trash'></i> Delete</a>"
                    },
                    "orderable": false,
                    "width": "150px",
                    "searchable": false
                }

            ],
            "language": {
                "emptyTable" : "No Data Found, please click on <b>Add New</b> button to Add."
            }
        });
    });

    function PopupForm(url) {
        var formDiv = $('<div/>');
        $.get(url)
        .done(function (response) {
            formDiv.html(response);

            Popup = formDiv.dialog({
                autoOpen: true,
                resizable: false,
                title: 'fill Movie details',
                height: 500,
                width: 700,
                close: function () {
                    Popup.dialog('destroy').remove();
                }
            });
        });
    }

    function SubmitForm(form) {
        $.validator.unobtrusive.parse(form);
        if ($(form).valid()) {
            $.ajax({
                type: "POST",
                url: form.action,
                data: $(form).serialize(),
                success: function (data) {
                    if (data.success) {
                        Popup.dialog('close');
                        dataTable.ajax.reload();
                        $.notify(data.message, {
                            globalPosition: "top-center",
                            className: "success"
                        })
                    }
                }
            });
        }

        return false;
    }

    function Delete(id) {
        if (confirm('Are you sure to delete this movie Record?')) {
            $.ajax({
                type: "POST",
                url: '@Url.Action("Delete","Movie")/' + id,
                success: function (data) {
                    if (data.success) {
                        dataTable.ajax.reload();
                        $.notify(data.message, {
                            globalPosition: "top-center",
                            className: "success"
                        })
                    }
                }
            });
        }
    }

}

0 个答案:

没有答案