我正在构建一个MVC Web应用程序以向用户显示调查表,并让他们填写调查表,然后通过存储过程将这些答案返回给DB。
问题在数据库中设置,我填充了要发送到视图的通用“问题”模型列表。
问题是我没有绑定到“ Html.EditorFor”的数据在回发到控制器后会丢失(请参见屏幕截图)。
我不想在视图上显示任何不必要/敏感的信息,也不需要显示所有Model属性,但是我确实需要这些属性中的数据才能发送回数据库(例如:TableID )
模型
public class QuestionModel
{
public int ID { get; set; }
public string Question { get; set; }
public string Answer { get; set; }
// Do not want to display these properties in the view
public int TableID { get; set; }
public string DBName { get; set; }
}
控制器
[HttpGet]
public ActionResult Index()
{
//I've hardcoded the model for this example, but
this data will be fetched from a DB via a stored procedure
List<QuestionModel> list = new List<QuestionModel>();
QuestionModel model1 = new QuestionModel
{
ID = 1,
Question = "What is your name?",
DBName = "Form 1",
TableID = 1
};
list.Add(model1);
QuestionModel model2 = new QuestionModel
{
ID = 2,
Question = "What is your favourite colour",
DBName = "Form 2",
TableID = 2
};
list.Add(model2);
return View(list);
}
[HttpPost]
public ActionResult Index(IList<QuestionModel> model)
{
//Call stored procedure to return user input to DB
return View();
}
查看
@model IList<MVCQuestion.Models.QuestionModel>
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<title></title>
</head>
<body>
@{
using (Html.BeginForm())
{
for(int i = 0; i < Model.Count; i++)
{
<h2>@Model[i].Question</h2>
@Html.EditorFor(x => Model[i].Answer);
}
<input type="submit" value="Submit" />
}
}
</body>
</html>
对此的“ hacky”解决方案是将每个属性绑定到“ Html.EditorFor”,并将这些字段设置为“ Read Only”和“ Hidden”,但是我觉得那是一个糟糕的解决方案,并且主要安全风险。
有更好的解决方案吗?