在mvc5上执行此操作之前,必须绑定数据源

本文关键字:绑定 数据源 mvc5 执行 操作 | 更新日期: 2023-09-27 18:29:06

这是我的控制器

using System;
using System.Collections.Generic;
using System.Data;
using System.Data.Entity;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using C3CardKYC.Models;
using System.Data.Entity.Validation;
using System.IO;
namespace C3CardKYC.Controllers
{
    public class HomeController : Controller
    {
        private ConnectString db = new ConnectString();
        //
        // GET: /Home/
        public ActionResult Index()
        {
            return View();  
        }
        public ActionResult Create()
        {
            ViewBag.doctype = new SelectList(db.DocMDs, "Id", "Nationality");
            return View();
        }
        //
        // POST: /Home/Create
        [HttpPost]
        [ValidateAntiForgeryToken]
        [ActionName("create")]
        public ActionResult Create(intermediate inter)
        {
            string imagePath = null;
            try { 
            if (ModelState.IsValid)
            {
                if (inter.pimage != null)
                {
                    var uploadDir = "~/uploads";
                    imagePath = Path.Combine(Server.MapPath(uploadDir), inter.pimage);
                    var imageUrl = Path.Combine(uploadDir, inter.pimage);
                }
                var part1 = new DetailsEntry()
                {
                    ClientName = inter.ClientName,
                    EmployeeId = inter.EmployeeId,
                    EmpCitizenId = inter.EmpCitizenId,
                    EmpName = inter.EmpName,
                    Nationality = inter.Nationality,
                    DocumentType = inter.DocumentType,

                };
                var part2 = new Passport()
                {
                   pissueddate =inter.pissueddate,
                    pexpirydate=inter.pexpirydate,
                    pissuedlocation=inter.pissuedlocation,
                    pimage=inter.pimage
                };
                db.DetailsEntries.Add(part1);
                db.Passports.Add(part2);
                db.SaveChanges();
            }
                }
            catch (DbEntityValidationException ex)
            {
                // Retrieve the error messages as a list of strings.
                var errorMessages = ex.EntityValidationErrors
                        .SelectMany(x => x.ValidationErrors)
                        .Select(x => x.ErrorMessage);
                // Join the list to a single string.
                var fullErrorMessage = string.Join("; ", errorMessages);
                // Combine the original exception message with the new one.
                var exceptionMessage = string.Concat(ex.Message, " The validation errors are: ", fullErrorMessage);
                // Throw a new DbEntityValidationException with the improved exception message.
                throw new DbEntityValidationException(exceptionMessage, ex.EntityValidationErrors);
            }
            return View();
}

        public ActionResult Delete(string[] ids)
        {
            int[] id = null;
            if(ids!=null)
            {
                id = new int[ids.Length];
                int j = 0;
                foreach(string i in ids)
                {
                    int.TryParse(i, out id[j++]);
                }
            }
            if(id!=null && id.Length >0)
            {
                List<DetailsEntry> allselected = new List<DetailsEntry>();
                allselected = db.DetailsEntries.Where(x => id.Contains(x.ClientId)).ToList();
                foreach(var i in allselected)
                {
                    db.DetailsEntries.Remove(i);
                }
                db.SaveChanges();
            }
            return RedirectToAction("displaygrid");
        }
        protected override void Dispose(bool disposing)
        {
            db.Dispose();
            base.Dispose(disposing);
        }

        public ActionResult displaygrid()
        {
            List<DetailsEntry> details = new List<DetailsEntry>();
            details = db.DetailsEntries.ToList();
            return View(details);
        }
    }
}

这是我的观点

@model C3CardKYC.Models.intermediate
@Model C3CardKYC.Models.detailslistmodel

@{
    ViewBag.Title = "Create";
}
}
<html>
<head>
    <meta charset="utf-8">
     <link rel="stylesheet" href="//code.jquery.com/ui/1.11.4/themes/smoothness/jquery-ui.css">
    <script src="//code.jquery.com/jquery-1.10.2.js"></script>
    <script src="//code.jquery.com/ui/1.11.4/jquery-ui.js"></script>
    <link rel="stylesheet" href="/resources/demos/style.css">
    <style>
        table, td, th {
            border: 1px solid green;
            border-collapse: collapse;
            width: 30%;
        }

        th {
            border: 1px solid black;
            background-color: green;
            color: white;
        }
    </style>
    <title></title>
</head>
        <body>
        </body>

</html>
<script type="text/javascript" src="http://code.jquery.com/jquery-latest.min.js"></script>
<script type="text/javascript" src="http://code.jquery.com/jquery-1.8.2.js"></script>
<script src="//code.jquery.com/jquery-1.11.2.min.js" type="text/javascript"></script>
<script type="text/javascript" src="scripts/jquery-1.8.2.js"></script>
<script type="text/javascript">
    $(document).ready(function () {
        $("#passport").hide();
    });
    $(document).ready(function () {
        $('#MovieType').change(function () {
            var doctype = $(this).val();
            if(doctype=="0")
                $("#passport").show();

        });

    });
    </script>
    <script type="text/javascript">
    function showimagepreview(input) {
        if (input.files && input.files[0]) {
            var reader = new FileReader();
            reader.onload = function (e) {
                $('#image01').attr('src', e.target.result);
            }
            reader.readAsDataURL(input.files[0]);
        }
    }
    $("#txtimg").change(function () {
        readURL(this);
    });
         </script>
 @using (Html.BeginForm()) {
    @Html.AntiForgeryToken()
    @Html.ValidationSummary(true)
    <fieldset>
        <legend>intermediate</legend>
        <div class="editor-label">
            @Html.LabelFor(model => model.ClientName)
        </div>
        <div class="editor-field">
            @Html.EditorFor(model => model.ClientName)
            @Html.ValidationMessageFor(model => model.ClientName)
        </div>
        <div class="editor-label">
            @Html.LabelFor(model => model.EmployeeId)
        </div>
        <div class="editor-field">
            @Html.EditorFor(model => model.EmployeeId)
            @Html.ValidationMessageFor(model => model.EmployeeId)
        </div>
        <div class="editor-label">
            @Html.LabelFor(model => model.EmpCitizenId)
        </div>
        <div class="editor-field">
            @Html.EditorFor(model => model.EmpCitizenId)
            @Html.ValidationMessageFor(model => model.EmpCitizenId)
        </div>
        <div class="editor-label">
            @Html.LabelFor(model => model.EmpName)
        </div>
        <div class="editor-field">
            @Html.EditorFor(model => model.EmpName)
            @Html.ValidationMessageFor(model => model.EmpName)
        </div>
        <div class="editor-label">
            @Html.LabelFor(model => model.Nationality)
        </div>
        <div class="editor-field">
            @Html.EditorFor(model => model.Nationality)
            @Html.ValidationMessageFor(model => model.Nationality)
        </div>
        <div class="editor-label">
            @Html.LabelFor(model => model.DocumentType)
        </div>
        <div class="editor-field">
            @Html.EditorFor(model => model.DocumentType)
            @Html.ValidationMessageFor(model => model.DocumentType)
        </div>
       @*@*Select Document Type: @Html.DropDownList("doctype", "Select")*@
        @*@Html.DropDownListFor(model => model.ddp, new SelectList(
                  new List<Object>{
                       new { value = 0 , text = "Passport"  },
                       new { value = 1 , text = "Pan" }
                       },
                  "value",
                  "text",
                   2))*@
        <select id="MovieType" name="MovieType">

            <option  value="0" >Passport</option>
            <option value="1">Pan</option>
            <option selected="selected" value="2">Comedy</option>

        </select>

         <div id="passport">
             <div class="editor-label">
                 @Html.LabelFor(model => model.pissueddate)
             </div>
             <div class="editor-field">
                 @Html.TextBoxFor(model => model.pissueddate, new { @id = "datepicker1" })
                 @Html.ValidationMessageFor(model => model.pissueddate)
             </div>
             <div class="editor-label">
                 @Html.LabelFor(model => model.pissuedlocation)
             </div>
             <div class="editor-field">
                 @Html.EditorFor(model => model.pissuedlocation)
                 @Html.ValidationMessageFor(model => model.pissuedlocation)
             </div>
             <div class="editor-label">
                 @Html.LabelFor(model => model.pexpirydate)
             </div>
             <div class="editor-field">
                 @Html.EditorFor(model => model.pexpirydate)
                 @Html.ValidationMessageFor(model => model.pexpirydate)

             </div>
             <div class="editor-label">
                 @Html.LabelFor(model => model.pimage, new {  })
             </div>
             <div>
@*@Html.LabelFor(model => model.pimage)*@
@Html.TextBoxFor(model => model.pimage, new { type = "file", @onchange = "showimagepreview(this);", @id = "txtimg" })
 </div>
             </div>
        <p>
            <input type="submit" value="Create" />
        </p>
    </fieldset>
}
<img id="image01" style="width:200px;height:200px;" />
@Html.Partial("~/Views/Home/displaygrid.cshtml");

这是我的显示网格

@model IEnumerable<C3CardKYC.Models.DetailsEntry>
@{
    ViewBag.Title = "displaygrid";
    //var grid = new WebGrid(source: Model, rowsPerPage: 10);
    WebGrid grid = new WebGrid(Model);
}
<html>
<head>
    <title>WebGrid</title>
</head>
<body>
    @using (Html.BeginForm("Delete", "Home", FormMethod.Get))
    {
        @grid.GetHtml(tableStyle: "gridtable", columns: grid.Columns(grid.Column(format: @<text><input type="checkbox" name="ids" value="@item.ClientId" /></text>, header: "select"),
         grid.Column("ClientId", "ClientId"),
         grid.Column("ClientName", "ClientName"),
         grid.Column("EmployeeId", "EmployeeId"),
         grid.Column("EmpCitizenId", "EmpCitizenId"),
         grid.Column("EmpName", "EmpName"),
         grid.Column("Nationality", "Nationality"),
         grid.Column("DocumentType", "DocumentType")
 )
 )
        <input type="submit" value="delete" />
    }
</body>
</html>
<h2>displayingrid</h2>

我得到了以下错误在mvc5上执行此操作之前,必须绑定数据源。在同一个页面上,我想显示一个表单和一个网络网格。所以我创建了一个局部视图,并在一个视图中渲染,但当我运行时,出现了错误。请建议我解决这个错误。

在mvc5上执行此操作之前,必须绑定数据源

您既没有将模型发送到视图,也没有将其发送到部分视图。

编辑:

首先,你不能像使用那样在同一视图中有两个模型

@型号C3CardKYC.型号中间@型号C3CardKYC.型号详细信息列表型号

您可以创建一个包含这两个容器的容器,然后将该容器放在视图中。

其次,您需要在控制器操作中获取/生成模型,然后将该模型传递给视图。

我想在主Crate视图中,您希望使用C3CardKYC.Models.intermediate,然后将C3CardKYC.Models.detailslistmodel传递到局部视图。

如果是这样的话,你可以定义一个类:

public class ContainerClass {
     public C3CardKYC.Models.detailslistmodel model1 { get; set; }
     public C3CardKYC.Models.detailslistmodel model2 { get; set; }
}

在您看来,它将被用作一个模型:

@model namespace.ContainerClass

然后在控制器操作中,您需要生成此类的对象(ContainerClass),设置model1和model2属性,并将生成的对象传递给视图:

return View(modelObject);

完成所有这些后,在您的视图中,您可以使用Model.model1访问中间模型,使用Model.mode2访问详细列表模型。

最后,您还必须将模型传递到局部视图:

@Html.Partial("path", Model.model2)