编辑视图未正确传递数据

时间:2017-03-01 14:49:10

标签: c# asp.net-mvc visual-studio razor

我正在尝试通过编辑视图编辑元素。在调试时,我注意到我正在尝试更新数据库的对象具有null或zeroed字段。编辑视图似乎不会返回我正在输入的数据。 型号:

using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using System.ComponentModel.DataAnnotations.Schema;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.Data.Entity;
using Microsoft.Data.Entity.Infrastructure;

namespace METALIMPEX.Models
{
    public class Condition
    {
        [Key]
        [Display(Name = "Condition ID")]
        [Column("condition_id")]
        [Required]
        public int conditionID { get; set; }

        [Display(Name = "Date and time")]
        [Column("condition_date")]
        [Timestamp]
        [Required]
        public DateTime dateTime { get; set; }

        [Display(Name = "Component ID")]
        [Column("component")]
        [Required]
        public int componentID { get; set; }

        [Display(Name = "Operator ID")]
        [Column("operator")]
        [Required]
        public int operatorID { get; set; }


        [Display(Name = "Component status")]
        [Column("condition")]
        [Required]
        public bool condition { get; set; }

        [Display(Name = "Comments")]
        [Column("remarks")]
        [Required]
        public string comments { get; set; }
    }
    public class ConditionDBContext : DbContext
    {
        public DbSet<Condition> Conditions { get; set; }
        protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder)
        {
            optionsBuilder.UseSqlServer("Data Source=DELL-XPS\\SQLEXPRESS;Initial Catalog=METALIMPEX;Integrated Security=True");
        }
    }
}

控制器:

using System.Linq;
using Microsoft.AspNet.Mvc;
using Microsoft.AspNet.Mvc.Rendering;
using Microsoft.Data.Entity;
using METALIMPEX.Models;
using System.Data.SqlClient;
using System.Collections.Generic;
using System.Web;
using System;

namespace METALIMPEX.Controllers
{
    public class ConditionController : Controller
    {
        private ApplicationDbContext _context;
        private ConditionDBContext db = new ConditionDBContext();
        IList<Condition> conditionList = new List<Condition>();

        public ConditionController(ApplicationDbContext context)
        {
            _context = context;
            //DEPRECATED CODE, MANUAL QUERY, PROJECT NOW USES DBCONTEXT
            /*string strConnection = "Data Source=DELL-XPS\\SQLEXPRESS;Initial Catalog=METALIMPEX;Integrated Security=True";
            string sqlQuery = "SELECT   REPLICATE('0',6-LEN(RTRIM(PartID))) + RTRIM(PartID) AS 'Part ID', REPLICATE('0', 6 - LEN(RTRIM(OperatorID))) + RTRIM(OperatorID) AS 'Operator ID', Date_Time AS 'Time', IsPartWorking AS 'Part Status', IsMachineWorking AS 'Machine Status' FROM Defect";
            SqlConnection sqlConnection = new SqlConnection(strConnection);
            SqlCommand command = new SqlCommand(sqlQuery, sqlConnection);
            SqlDataReader Dr;
            try {
                sqlConnection.Open();
                Dr = command.ExecuteReader();
                while (Dr.Read())
                {

                    conditionList.Add(new Defect()
                    {
                        conditionID = Dr["Part ID"].ToString(),
                        operatorID = Dr["Operator ID"].ToString(),
                        dateTime = Dr["Time"].ToString(),
                        partStatus = (bool)Dr["Part Status"],
                        machineStatus = (bool)Dr["Machine Status"]
                    });
                };
                Dr.Dispose();
            }
            catch (SqlException) {
                throw new InvalidOperationException("An error has occured while connecting to the database");
                //OR
                //return View("Error");
            }*/
        }

        // GET: Condition
        public IActionResult Index()
        {
        //return View(conditionList);
        return View(db.Conditions.ToList());
        }

        // GET: Condition/Details/5
        public IActionResult Details()
        {
            return View(conditionList);
        }

        // GET: Condition/Create
        public IActionResult Create()
        {
            return View();
        }

        // POST: Condition/Create
        [HttpPost]
        [ValidateAntiForgeryToken]
        public IActionResult Create(Condition condition)
        {
            if (ModelState.IsValid)
            {
               //_context.Condition.Add(condition);
               //_context.SaveChanges();
                return RedirectToAction("Index");
            }
            return View(condition);
        }

        // GET: Condition/Edit/5
        public IActionResult Edit(int id)
        {
            if (conditionList == null)
            {
                return HttpNotFound();
            }
            Condition condition = db.Conditions.Single(m => m.conditionID == id);
            return View(condition);
        }

        // POST: condition/Edit/5
        [HttpPost]
        [ValidateAntiForgeryToken]
        public IActionResult Edit(Condition condition)
        {
            if (ModelState.IsValid)
            {
                db.Update(condition);
                db.Entry(condition).State = EntityState.Modified;
                db.SaveChanges();
                return RedirectToAction("Index");
            }
            return View(condition);
        }

        // GET: condition/Delete/5
        [ActionName("Delete")]
        public IActionResult Delete(string id)
        {
            return View(conditionList);
        }

        // POST: condition/Delete/5
        [HttpPost, ActionName("Delete")]
        [ValidateAntiForgeryToken]
        public IActionResult DeleteConfirmed(string id)
        {
            /*Movie movie = db.Movies.Find(id);
            if (movie == null)
            {
                return HttpNotFound();
            }
            db.Movies.Remove(movie);
            db.SaveChanges();
            return RedirectToAction("Index");*/
            return RedirectToAction("Index");
        }

    }
}

查看:

@model METALIMPEX.Models.Condition

@{
    ViewData["Title"] = "Edit";
}

<h2>Edit</h2>

<form asp-action="Edit">
    <div class="form-horizontal">
        <h4>Condition</h4>
        <hr />
        <div asp-validation-summary="ValidationSummary.ModelOnly" class="text-danger"></div>
        <input type="hidden" asp-for="conditionID" />
        <div class="form-group">
            <label asp-for="componentID" class="col-md-2 control-label"></label>
            <div class="col-md-10">
                <input asp-for="componentID" class="form-control" />
                <span asp-validation-for="componentID" class="text-danger" />
            </div>
        </div>
        <div class="form-group">
            <label asp-for="operatorID" class="col-md-2 control-label"></label>
            <div class="col-md-10">
                <input asp-for="operatorID" class="form-control" />
                <span asp-validation-for="operatorID" class="text-danger" />
            </div>
        </div>
        <div class="form-group">
            <div class="col-md-offset-2 col-md-10">
                <div class="checkbox">
                    <input asp-for="condition" />
                    <label asp-for="condition"></label>
                </div>
            </div>
        </div>
        <div class="form-group">
            <label asp-for="dateTime" class="col-md-2 control-label"></label>
            <div class="col-md-10">
                <input asp-for="dateTime" class="form-control" />
                <span asp-validation-for="dateTime" class="text-danger" />
            </div>
        </div>
        <div class="form-group">
            <label asp-for="comments" class="col-md-2 control-label"></label>
            <div class="col-md-10">
                <input asp-for="comments" class="form-control" />
                <span asp-validation-for="comments" class="text-danger" />
            </div>
        </div>
        <div class="form-group">
            <div class="col-md-offset-2 col-md-10">
                <input type="submit" value="Save" class="btn btn-default" />
            </div>
        </div>
    </div>
</form>

<div>
    <a asp-action="Index">Back to List</a>
</div>

@section Scripts {
    <script src="~/lib/jquery/dist/jquery.min.js"></script>
    <script src="~/lib/jquery-validation/dist/jquery.validate.min.js"></script>
    <script src="~/lib/jquery-validation-unobtrusive/jquery.validate.unobtrusive.min.js"></script>
}

我是.NET的初学者,所以我不知道这里有什么问题。编辑视图是由框架生成的,所以我认为它应该正常工作。

有什么想法吗?

1 个答案:

答案 0 :(得分:0)

问题在于修改操作方法的参数名称。以下是点击保存按钮时从视图中发布的网址编码表单数据。

  

conditionID =安培;日期时间= 2013年12月1日和安培; COMPONENTID = 1&安培; operatorID = 1&安培;条件=真安培;注释=

操作参数名称为条件,并且传入的表单数据中存在键值对 condition = true MVC model binding进程将尝试将参数/属性(在复杂模型的情况下)映射到相应的路由/查询字符串/请求正文数据。

因此,它试图将表单数据中条件的值(即 true )映射到action参数,最终无法转换为bool 对象

将参数名称更改为与表单数据中的任何键名称不对应的任何名称,它应该有效。