c# - 我应该如何使用这个简单的 Create View 为我的 ASP.NET MVC3 View 编写这个 Controller ActionResult 方法?

标签 c# .net asp.net-mvc-3 controller

我不确定我是否应该使用 FormsCollection或者别的什么,有了这个基本的 Create查看。

(注意:我使用 custom editor template 作为标签 ICollection<string> )

型号

public class Question
{
    [Required, StringLength(100)]
    public string Title { get; set; }
    [Required]
    public string Body { get; set; }
    public ICollection<string> Tags { get; set; }
}

查看

@model AWing.Core.Entities.Product

@{
    ViewBag.Title = "Create";
    Layout = "~/Views/Shared/_Layout.cshtml";
}

<h2>Create</h2>

@using (Html.BeginForm()) {
    @Html.ValidationSummary(true)
    <fieldset>
        <legend>Question</legend>

        <div class="editor-label">
            @Html.LabelFor(model => model.Name)
        </div>
        <div class="editor-field">
            @Html.EditorFor(model => model.Name)
            @Html.ValidationMessageFor(model => model.Name)
        </div>

        <div class="editor-label">
            @Html.LabelFor(model => model.Description)
        </div>
        <div class="editor-field">
            @Html.EditorFor(model => model.Description)
            @Html.ValidationMessageFor(model => model.Description)
        </div>

        <div class="editor-label">
            @Html.LabelFor(model => model.Tags)
        </div>
        <div class="editor-field">
            @Html.EditorFor(model => model.Tags, "tags")
            @Html.ValidationMessageFor(model => model.Tags)
        </div>

        <p>
            <input type="submit" value="Create a new product" />
        </p>
    </fieldset>
}

Controller

[HttpPost]
public ActionResult Create(FormsCollection formsCollection)
{
  ... ????
}

还是别的?

[HttpPost]
public ActionResult Create(... ??? ...)
{
  .... ????
}

最佳答案

因为你有一个强类型 View ,你可以有你的 [HttpPost]方法采用与变量相同的类型,例如:

[HttpPost]
public ActionResult Create(Product model)  
{  
    if (ModelState.IsValid)
    {
        // add new product
        .... ????
    } 
}  

DefaultModelBinder将获取返回的值,并将它们插入到您的强类型模型中。中提琴!

只要您的标签集合模板的模型是 string 类型, MVC 将遍历集合,以便可以对其进行绑定(bind)(尽管您可能必须将 ICollection 更改为 List)。

更新

正如我们在评论中讨论的那样,与其为每个标签创建一个文本框,不如创建一个单独的 ViewModel,其中包含所有其他 Product 属性。

而不是使用 List<string> Tags在您的 ViewModel 中,创建此属性:

public string TagCollection { get; set; }

在您看来,有一个 TagCollection 的文本框.然后,在您的创建操作中,您可以将 TagCollection 字符串解析到您的标签列表中。

关于c# - 我应该如何使用这个简单的 Create View 为我的 ASP.NET MVC3 View 编写这个 Controller ActionResult 方法?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7695266/

相关文章:

c# - 我应该为 C# 脚本使用什么方法

c# - 通过反射获取命名空间中的所有类型

c# - 如何实现 "masterpage"级别的逻辑

javascript - ASP.NET MVC 3 Razor : How to get Action URL in a Javascript string variable?

c# - Windows 10 平板电脑上的 Windows Phone 8.1 Silverlight 应用程序

c# - 使用 Winforms 应用程序分发 Access 数据库

c# - DownloadFile 创建 0 字节文件

ASP.NET MVC3如何使用间隔一小时的计时器执行 Controller 的操作方法

c# - AWS Lambda 文件上传到 ASP.NET Core 2.1 Razor Page 会损坏二进制文件

C#:SQL - 一次一个查询与命令文本中的多个查询?