我使用UseCaseId
和ExtensionPoint
的模型值填充我的视图 - 通过此调试似乎工作正常。
但是,当我向视图中的ExtensionTitle
字段添加新信息然后POST时,只会保留ExtensionTitle
的值以及UseCaseId
和{的值{1}}丢失了。这意味着ExtensionPoint
返回false,因此我无法将新记录保存到数据库中。
有人可以告诉我为什么这些值会在我if (ModelState.IsValid)
时迷失吗?
视图模型
POST
MODEL
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Linq;
using System.Web;
namespace JustSpecIt.ViewModels
{
public class AddExtensionStepViewModel
{
public int UseCaseId { get; set; }
[DisplayName ("Extends Step #")]
public int ExtensionPoint { get; set; }
[DisplayName ("Extends Step Description")]
public string StepTitle { get; set; }
[DisplayName("Extension Name")]
public string ExtensionTitle { get; set; }
}
}
CONTROLLER
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
namespace JustSpecIt.Models
{
public class Extension
{
public int ID { get; set; }
public int UseCaseID { get; set; }
public string Title { get; set; }
public int ExtensionPoint { get; set; }
}
}
查看
// GET: Extensions/Create
public ActionResult Create(int id)
{
ViewBag.UseCaseId = id;
ViewBag.StepTitle = db.Steps.Find(id).Content;
//Create an populate the ViewModel
AddExtensionStepViewModel model = new AddExtensionStepViewModel()
{
ExtensionPoint = id,
UseCaseId = db.Steps.Find(id).UseCaseID,
};
return View();
}
// POST: Extensions/Create
// To protect from overposting attacks, please enable the specific properties you want to bind to, for
// more details see http://go.microsoft.com/fwlink/?LinkId=317598.
[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult Create([Bind(Include = "UseCaseId,ExtensionTitle,ExtensionPoint")] AddExtensionStepViewModel model)
{
if (ModelState.IsValid)
{
Extension e = new Extension ();
e.ExtensionPoint = model.ExtensionPoint;
e.UseCaseID = model.UseCaseId;
e.Title = model.ExtensionTitle;
db.Extensions.Add(e);
db.SaveChanges();
return RedirectToAction("ChooseExtensionStep", new { id = model.UseCaseId });
}
return View(model);
}
答案 0 :(得分:1)
您尚未将模型传递给GET方法中的视图(因此UseCaseID
和Title
的值为0
(int
的默认值)
public ActionResult Create(int id)
{
ViewBag.UseCaseId = id;
ViewBag.StepTitle = db.Steps.Find(id).Content;
AddExtensionStepViewModel model = new AddExtensionStepViewModel()
{
ExtensionPoint = id,
UseCaseId = db.Steps.Find(id).UseCaseID,
};
return View(model); // change this
}