模型对象初始化

时间:2014-08-01 14:43:11

标签: c# asp.net asp.net-mvc asp.net-mvc-4

我正在使用代码优先方法创建我的第一个基本ASP MVC应用程序。

我无法理解控制器/视图上下文中的内容。

好的,这是我的视图脚本的一部分,其中包含一个基本形式:

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

    @Html.TextBoxFor(model => model.customerId, new { @Value = ViewBag.customerId })
    @Html.EditorFor(model => model.customerEmailAddress)

    <input type="submit" value="Next" />
}

只是一个带有几个字段和提交按钮的简单表单。

这是我的控制者:

// GET
public ActionResult Index(int? customerId) // The customerId param is passed from the URL, irrelevant to the question
{

    if(customerId == null)
    {
        customerId = generateCustomerId();
    }

    // At this point, I need to save this customer ID to the
    // one of the Customer objects attributes, however,
    // I cannot access the Customer object here?
    return View();
}

// POST
[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult Index(Customer Customer)
{
    // This customer parameter represents the object model Customer
    // which I use in my database schema - but where did it come from?
    // How can I access this in my GET index actionresult above?
    // ---
}

代码中的注释解释了我正在尝试做什么 - Customer对象参数在post索引方法中来自何处?是否只是由ASP自动生成和初始化? 如何在GET Index方法中访问此对象?我猜我不得不以某种方式自己初始化它?

2 个答案:

答案 0 :(得分:1)

Q / Customer对象参数来自post index方法的位置? 它不会通过MVC自动初始化,它将来自您提交索引页面时的表单,然后它将发布到此Action方法。

问:如何在GET Index方法中访问此对象? 您可以将所有索引都包含在CustomerId中,因此您可以查询数据库以获取特定客户并随意使用它。

答案 1 :(得分:1)

以稍微不同的方式解释......

剃刀视图中的表单将打包您的模型(使用您键入的更改)并将其POST到第二个操作 - 这就是Customer对象是参数的原因 - 它将包含您更新的客户数据。

第一个操作希望您实现一种方法来查找特定客户(带有id)并创建客户模型,然后将其传递给视图。

相关问题