具有加载和表单模型的MVC视图

杰斐逊

我有一个像表单一样工作的视图,因此它加载了一堆下拉菜单,并从FormViewModel类中进行选择,该类是从中的Controllers返回的ActionResult Index将所有数据输入表单后,我将使用Html.BeginForm("Create"调用save方法。ActionResult Create(RequestForm model)因此,问题是我想使用两种模型,一种用于加载,另一种用于保存数据。我现在正在做的是从FormViewModel和RequestForm模型中放入对象。

有一个更好的方法吗?

视图:

@model  FormViewModel
@using (Html.BeginForm("Create", "RequestForm", FormMethod.Post))
{
    @Html.ValidationSummary(true);
     <div class="k-content">
     <h4>* Country</h4>
     @Html.TextBoxFor(x => x.CountryId, new { id = "ddlCountry", @class = "form-control" })
     @Html.ValidationMessageFor(model => model.CountryId)
     </div>
}

FormViewModel

[Required]
public int? CountryId { get; set; }

public List<CountryModel> ListOfCountries { get; set; }

RequestForm模型

public class RequestForm
{
    [Required]
    public int? CountryId { get; set; }
}
    

控制器

public ActionResult Create(RequestForm model)
{
    var FormInfo = FormCreate(model);
    return View("");
}
David Liang

您可以嵌套视图模型,仅在表单发布中提交所需的视图模型。

例如:

public class FormViewModel
{
    public IEnumerable<CountryViewModel> AvailableCountries { get; set; }
    public CreateRequestViewModel Data { get; set; }
}

public class CountryViewModel
{
    public int CountryId { get; set; }
    public string CountryName { get; set; }
}

public class CreateRequestViewModel
{
    [Required]
    public int SelectedCountryId { get; set; }
}

我刚刚编好名字,但希望您能明白。


然后在视图上,可以按如下所示进行设置:

@model FormViewModel
@using (Html.BeginForm("Create", "RequestForm", FormMethod.Post))
{
    @Html.ValidationSummary(true);
    
    <div class="k-content">
        <h4>* Country</h4>
        @Html.DropDownListFor(
            x => x.Data.SelectedCountryId,
            new SelectList(Model.AvailableCountries, "CountryId", "CountryName"),
            new { id = "ddlCountry", @class = "form-control" }
        )
        @Html.ValidationMessageFor(x => x.Data.SelectedCountryId)
    </div>
}

同样,我手动编写了它,因此可能会出现编译错误。但想法是,您使用DropDownListFor()而不是TextBoxFor()来生成一个下拉列表,其中包含由AvailableCountries您填充列表生成的选项

而且您只需要放置要向其[Required]发布数据的视图模型,因为这可以验证用户的数据。您无需将其放在上,CountryViewModel因为您自己在填充列表。


最后,还有一个更重要的,你需要注意的事情,那就是对的形式发布给该方法的参数名:

public ActionResult Create(CreateRequestViewModel data)
{
    ...
}

参数的名称必须您在外部模型中声明的名称匹配FormViewModel

本文收集自互联网,转载请注明来源。

如有侵权,请联系 [email protected] 删除。

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章