从控制器中的强类型视图中获取数据

时间:2012-12-06 10:13:50

标签: asp.net-mvc razor asp.net-mvc-4

我有强类型视图,我想获取控制器中的数据。 这就是我所拥有的:

@model WordAutomation.Models.Document

@{
    ViewBag.Title = "Document";
}

<h2>Document</h2>

@using (Html.BeginForm()) {
    @Html.ValidationSummary(true)

    <fieldset>
        <legend>Document</legend>

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

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


@section Scripts {
    @Scripts.Render("~/bundles/jqueryval")
}

然后,在控制器中我有这个:

[HttpPost]
        public ActionResult Document(FormCollection formValue)
        {
            string test = formValue[0].ToString();
            return View();
        }

但没有数据出现。知道我做错了什么吗? 感谢

2 个答案:

答案 0 :(得分:4)

让MVC为您处理模型绑定。您可以简单地传递视图模型的实例,而不是将FormCollection传递给控制器​​。将控制器操作更改为:

[HttpPost]
public ActionResult Document(WordAutomation.Models.Document model)
{
    string test = model.CaseNumber;

    return View(model); // return your model back to the view to persist values
}

MVC会自动将FormCollection中的值绑定到WordAutomation.Models.Document。然后,您可以简单地将模型传递回POST后的视图,以便在需要时保留输入值(在示例中包含此内容)。

答案 1 :(得分:0)

强类型时,从视图到控制器的数据非常容易。 您需要做的就是通过model.yourpropertyname获取控制器中的数据。

代码在模型中将如下所示

[HttpPost]
    public ActionResult Document(Document aDocumentModel)
    {
        string test = aDocumentModel.CaseNumber;
        return View();
    }

现在数据可用于&#34;字符串测试&#34;你可以在需要的地方使用它, 还有一件事你需要 告诉控制器关于&#34; Document&#34; -model的命名空间,所以你需要添加

using WordAutomation.Models;//Your Model's namespace here

在控制器的命名空间部分。

希望它有所帮助!!!