2

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

@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();
        }

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

4

2 回答 2

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
}

FormCollectionMVC 会自动为你绑定你的值WordAutomation.Models.Document。然后,如果需要,您可以在 POST 之后将模型简单地传递回视图以保留输入值(已在示例中包含此值)。

于 2012-12-06T10:28:07.113 回答
0

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

代码在模型中将如下所示

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

现在数据在“字符串测试”中可用,您可以在需要的地方使用它,还有一件事您需要告诉控制器“文档”模型的命名空间,因此您需要添加

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

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

希望能帮助到你!!!

于 2012-12-06T13:24:21.950 回答