I'm building an MVC web app to display a questionnaire to a user, and have them fill it out, and return those answers to a DB via a stored procedure.
The questions are set in the DB, and I populate a list of generic "Question" Models to send to the view.
The problem is that data that I don't bind to a "Html.EditorFor" gets lost on post back to the controller (see screenshot).
I don't want to display any unneccessary/sensitive information on the view, and I don't need to show all Model properties, but I do need the data in those properties to send back to the DB (E.G: TableID)
Model
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; }
}
Controller
[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();
}
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>
A "hacky" solution to this is to bind each property to a "Html.EditorFor", and set those fields to "Read Only", and "Hidden", but I feel like that is a poor solution, and a major security risk.
Is there a better solution to this?