Asp.net mvc 从控制器中的强类型视图获取数据

Asp.net mvc 从控制器中的强类型视图获取数据,asp.net-mvc,razor,asp.net-mvc-4,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>Docum

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

@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")
}
但是没有数据。知道我做错了什么吗?
谢谢

让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后将模型传递回视图,以保留输入值(如果需要),并将其包含在示例中。

让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后将模型传递回视图,以保留输入值(如果需要),并将其包含在示例中。

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

在模型中,代码如下所示

[HttpPost]
    public ActionResult Document(Document aDocumentModel)
    {
        string test = aDocumentModel.CaseNumber;
        return View();
    }
现在数据在字符串测试中可用,您可以在需要的地方使用它, 还有一件事你需要做 告诉控制器文档模型的名称空间,因此需要添加

using WordAutomation.Models;//Your Model's namespace here
在控制器的命名空间部分


希望对你有帮助

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

在模型中,代码如下所示

[HttpPost]
    public ActionResult Document(Document aDocumentModel)
    {
        string test = aDocumentModel.CaseNumber;
        return View();
    }
现在数据在字符串测试中可用,您可以在需要的地方使用它, 还有一件事你需要做 告诉控制器文档模型的名称空间,因此需要添加

using WordAutomation.Models;//Your Model's namespace here
在控制器的命名空间部分


希望对你有帮助

你能添加你的全视图代码吗?@AliRizaAdiyahsi Merhaba AliRiza,请现在检查:你为什么发布模型而不是像这样的formCollection:public ActionResult Document model我说的是@Terric answer。你能添加你的全视图代码吗?@AliRizaAdiyahsi Merhaba AliRiza,现在请检查:为什么你发布模型而不是像这样的formCollection:public ActionResult DocumentDocument model我说的是@Terric answer.MVC非常简单,我让它看起来更复杂:。Thanks@Laziale我们都去过那里;很高兴你的问题得到了解决。我希望,我写下我的评论作为回答:我也认为更复杂。MVC是如此简单,我正在让它看起来更复杂:。Thanks@Laziale我们都去过那里;很高兴你的问题得到了解决。我希望,我写下我的评论作为回答:我也觉得更复杂。