ASP.从键/值对.NET MVC视图模型



如何将键/值对表示为ASP ?. NET MVC模型?我的表单数据不支持强类型模型。

我的第一个解决方案是使用Razor设计我的表单,并使用一些扩展方法来获取FormElement值。

@model IEnumerable<FormElementKeyValues>
@Html.TextBox(Model.GenerateID("Email"), Model.GetFormElementValue("Email"))<br />

这是有效的,但是当我想处理来自POST的数据时,它变得混乱。我没有模型,所以我被迫退回到使用FormCollection,这意味着我失去了强类型模型和验证的好处。

第二个解决方案(我还没有尝试过)是创建我的个人表单模型,并使用自定义属性装饰属性,帮助我访问键/值对。

public SimpleFormModel {
    [FormElement("Fullname")]
    [Required(ErrorMessage = "Required")]
    public string Fullname { get; set; }
    [FormElement("Email")]
    [Required(ErrorMessage = "Required")]
    [DisplayName("E-mail")]
    public string Email { get; set; }
}
public ComplexFormModel {
    [FormElement("Firstname")]
    [Required(ErrorMessage = "Required")]
    public string Firstname { get; set; }
    [FormElement("Surname")]
    [Required(ErrorMessage = "Required")]
    public string Surname { get; set; }
    [FormElement("Email")]
    [Required(ErrorMessage = "Required")]
    [DisplayName("E-mail")]
    public string Email { get; set; }
}

这将允许我在我的视图中使用强类型模型以及标准的Razor Html helper。

<div class="editor-field">
  @(Html.TextBoxFor(model => model.Firstname))
  @(Html.ValidationMessageFor(model => model.Firstname))
  @(Html.DisplayFor(model => model.Firstname))
</div>

我觉得你把这个任务复杂化了…

模型在那里为你渲染,并从你的剃刀视图消费…

例如,假设我有一个出售节日门票的网站,我有一个订单表单,我想在所有不同的活动中重复使用,我想在该表单中预填充活动的名称…你应该这样做……

首先你需要一个模型,

public class RegistrationViewModel {
    [Display(Name = "Event")]
    public string EventName { get; set; }
    [Required]
    [Display(Name = "First name")]
    public string FirstName { get; set; }
    [Required]
    [Display(Name = "Last name")]
    public string LastName { get; set; }
}

接下来让我们假设我们有一个Events控制器它的动作叫做Register

public class Events : Controller 
{
    public ActionResult Register(int id)
    {
        Event event = DbSource.FindEventById(id);
        RegistrationViewModel model = new RegistrationViewModel 
        {
            EventName = event.Name
        }
        return this.View(model);
    }
    [HttpPost]
    [ValidateAntiForgeryToken]
    public ActionResult Register(RegistrationViewModel model)
    {
        if( ! ModelState.IsValid ) 
        {
            return this.View(model);
        }
        // ship the tickets, return thank you view, etc...
    }
}

最后是视图....

@model RegistrationViewModel
@using (Html.BeginForm("Register", "Events")
{
    <div>
        @(Html.AntiForgeryToken())
        @(Html.LabelFor(model => model.EventName))
        @(Html.ValueFor(model => model.EventName))
        @(Html.LabelFor(model => model.FirstName))
        @(Html.TextBoxFor(model => model.FirstName))
        @(Html.ValidationMessageFor(model => model.FirstName))
        @(Html.LabelFor(model => model.LastName))
        @(Html.TextBoxFor(model => model.LastName))
        @(Html.ValidationMessageFor(model => model.LastName))
    </div>
}

我是临时写的所以我不知道它是否能正常编译,但我给你们看的基本上就是它的全部内容。

最新更新