通过视图传递初始化的模型



简单的问题,但我找不到解决方案。我有1 Get ActionResult, 1 Post ActionResult和1视图。在Get方法中,我初始化了模型中的某些部分。然后在视图中初始化另一部分。当模型进入Post方法时,它没有很好地初始化。如何通过视图和方法传递数据?我不想使用临时对象。

的例子:

[HttpGet]
    public ActionResult Register(Guid product_id)
    {
        RegistrationModel model = new RegistrationModel();
        model.Product = **someProduct**;
        return View(model);
    }
    [HttpPost]
    public string Register(RegistrationModel model, Product Product)
    {
                 Here the objects comes initialized only with the parts from the view...
    }

您需要了解MVC是如何工作的。有一个叫做模型绑定的概念,它负责用合适的 HTML映射Model

当我说时,我的意思是它需要根据特定的规则进行格式化。为了简化事情,MVC内置了HtmlHelpers来处理Model的属性到HTML元素之间的转换。

从你的[HttpGet]方法你可以返回:

1)无模型视图return View();

2)具有Blank模型的视图return View(new Product());

3)包含一些数据的模型的视图return View(product);

在View中,你应该决定:

1)如果您只想显示模型,您可以使用(可能不包含在form中):

  • HtmlHelpers like @Html.DisplayFor(x => x.Name)

  • 简单模型调用,如<h1>@Model.Name</h1>

2)如果你想要一些数据传回到你的[HttpPost],你应该

注意将Model的属性"映射"到一个HTML元素,特别是(所有内容都包含在form中):

  • 通过HtmlHelpers@Html.TextBoxFor(x => x.Price),这将产生一个"合适的"HTML输出:<input id="Price" name="Price" value="">52.00</input>(推荐)

  • 通过格式化的HTML ( ^_^ ):


   <select id="SelectedLanguageId" name="SelectedLanguageId">
       <option value="1">English</option>
       <option value="2">Russian</option>
    </select>

总结:

1)如果你想接收一些回[HttpPost]方法,你应该有一个suitable HTML元素在你的。

2)如果你只想显示一些数据,你可以简单地调用模型的属性

3)使用HTML helper代替原始HTML代码。

<标题>注意!

复杂Model的模型绑定是通过EditorTemplates循环中的隐藏输入不同类型的序列化等实现的。

最新更新