绑定到可变长度列表的模型

时间:2018-06-28 01:54:33

标签: c# asp.net-core-mvc entity-framework-core

如何构建允许用户创建问题选项的UI?视图(Form.cshtml)应该允许可变数量的文本输入(随时两个或多个)绑定到可变数量的@ Model.Options [i] .OptionText。是否有Razor标记或标签助手可用于完成此任务? 之所以有“ Option”类,是因为Entity Framework Core不允许持久保留包括字符串在内的原始类型的集合。

Option.cs

namespace MyProject.Models
{
     public class Option
     {
         public int OptionId { get; set; }
         public string OptionText { get; set; }
         public int QuestionId { get; set; }
         public Question Question { get; set; }
     }
}

Question.cs

namespace MyProject.Models 
{
    public class Question
    {
        public int QuestionID { get; set; }
        public string Text { get; set; }
        public ICollection<Option> Options { get; set; }
    }
}

CreateQuestionModel.cs

public class CreateQuestionModel
{
    [Required]
    [UIHint("text")]
    public string Text { get; set; }

    [Required]
    [UIHint("hidden")]
    public int FormId { get; set; }

    public ICollection<Options> Options{ get; set; }
}

Form.cshmtl

@model CreateQuestionModel

<form asp-controller="Form" asp-action="Options" method="post">
    <div class="form-group">
        <label asp-for="@Model.Text">Question name</label>
        <input type="text" class="form-control" asp-for="@Model.Text">
    </div>
    <div class="form-group">
        <label asp-for="@Model.Options"></label>
        <input type="text" class="form-control" asp-for="???">
    </div>
    <div class="form-group">
        <label asp-for="@Model.Options"></label>
        <input type="text" class="form-control" asp-for="???">
    </div>

    <button type="submit" class="btn btn-primary">Create Options</button>
</form>

FormController.cs

[HttpPost]
[ValidateAntiForgeryToken]
public async Task<IActionResult> Options([Bind("Text, Choices")] Question question)
{
    if (ModelState.IsValid)
    {
        context.Add(question);
        await context.SaveChangesAsync();
        return RedirectToAction("/");
    }

    return RedirectToAction("/");
}

0 个答案:

没有答案