如何结合从用户输入分配的值和在 ASP.net MVC 4 中生成的值来创建新记录?

How to create new record with a combination of values being assigned from user input and being generated in ASP.net MVC 4?

我正在尝试将新记录添加到我创建的数据库中。数据库名为 QUESTIONNAIRES,它包含以下列:QuestionnaireUID、UserUID、QuestionnaireName、DateCreated、Link 和 Image。

我希望用户指定 QuestionnaireName 并提供图像,我想自己生成 QuestionnaireUID、UserUID、DateCreated 和 Link。到目前为止,这是代表此创建过程的我的 View():

@using (Html.BeginForm())
        {
            @Html.AntiForgeryToken()

                @Html.ValidationSummary(true, "", new { @class = "text-danger" })

                // Hide QuestionnaireUID, UserUID, and Link from user. These fields will be generated instead of assigned by user input.    
                @Html.HiddenFor(model => model.QuestionnaireUID)
                @Html.HiddenFor(model => model.UserUID)
                @Html.HiddenFor(model => model.Link)

                <div class="form-group"> <!-- Questionnaire name. -->
                    <h2>Name</h2>
                    <p> Please provide a name for your decision tree.<p>
                    <div class="col-md-10">
                        @Html.EditorFor(model => model.QuestionnaireName, new { htmlAttributes = new { @class = "form-control" } })
                        @Html.ValidationMessageFor(model => model.QuestionnaireName, "", new { @class = "text-danger" })
                    </div>
                </div>

                <div class="form-group"> <!-- Questionnaire image. -->
                    <h2>Image</h2>
                    <p> Please provide a background image for your decision tree.</p>

                    <!-- ADD FILE IMAGES & ENCODE IN BINARY. -->

                    <div class="col-md-10">
                        @Html.EditorFor(model => model.Image, new { htmlAttributes = new { @class = "form-control" } })
                        @Html.ValidationMessageFor(model => model.Image, "", new { @class = "text-danger" })
                    </div>
                </div>

                <div class="form-group btn_next"> <!-- Save and continue button. -->
                    <input type="submit" value="Save and Continue" class="btn">
                </div>
        }

下面还显示了正在使用的问卷控制器方法:

      // GET: Questionnaires/Create
        public ActionResult Create()
        {
            ViewBag.UserUID = new SelectList(db.Users, "UserUID", "FirstName");
            return View();
        }

        // POST: Questionnaires/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 = "QuestionnaireUID, UserUID, QuestionnaireName, DateCreated, Link, Image")] QUESTIONNAIRE questionnaire)
        {
            if (ModelState.IsValid)
            {
                db.QUESTIONNAIRES.Add(questionnaire);
                db.SaveChanges();
                return RedirectToAction("Index");
            }

            return View(questionnaire);
        }

如您所见,我隐藏了要在 View() 中生成的三个属性。我现在不知道我在哪里生成和分配这些值。我是在 View() 中还是在 Controller 方法中执行此操作?这个任务是什么样的?

我会在 HttpGet 上的控制器中生成这些值,并且我会使用 ViewModel。

呼应 , using a ViewModel is a good way of keeping everything logically consistent and separated. There's some pretty good in-depth discussions and explanations of 其他值得一读的 ViewModel。

例如,您的 ViewModel 可能看起来(大致)像这样:

public class QuestionnaireViewModel
{
    public Guid QuestionnaireUID { get; set; }
    public Guid UserUID { get; set; }
    public string QuestionnaireName { get; set; }
    public DateTime DateCreated { get; set; }
    public string Link { get; set; }
    public Image Image { get; set; }
}

它可以像这样传递给视图:

[HttpGet]
public ActionResult Create()
{
    var vm = new QuestionnaireViewModel();
    vm.QuestionnaireUID = Guid.NewGuid();
    vm.UserUID = Guid.NewGuid();
    return View(vm);
}

发布表单时,MVC 可以自动将传入的数据解释为 QuestionnaireViewModel:

[HttpPost]
public ActionResult Create(QuestionnaireViewModel vm)
{
    if (ModelState.IsValid)
    {
        // map the viewmodel properties onto the domain model object here
        db.SaveChanges();
        return RedirectToAction("Index");
    }

    return View(questionnaire);
}

还有几点:

  • In this example,您会发现甚至可能没有必要在 ViewModel 中包含 UID 内容,因为 ViewModel 只关心向用户收集的数据 from/presented。此外,除非 @Html.HiddenFor 在视图上有某种功能用途,否则您可以将它们排除在外并在 HttpPost 上生成它们。
  • 如果您正在寻找 "create new record with a combination of values being assigned from user input and being generated in ASP.NET MVC 4"(a.k.a。在 MVC 中创建表单),那么您的 model/viewmodel 越复杂,我 stay away from using ViewBag 用于这些目的。