gpt4 book ai didi

asp.net-mvc-3 - MVC 3 POST 数据和 Id 字段

转载 作者:行者123 更新时间:2023-12-05 09:24:46 25 4
gpt4 key购买 nike

我的 MVC 3 项目中有一个模型的强类型 razor View 。主要用于编辑模型。

该模型包含数据库键的 Id 字段和一些其他字符串字段(它是一个 viewModel 和所有但那不是问题的重点)。

在 View 中,我只有一个表单和一个提交按钮,没有别的。当 View 发布到 Controller 时, Controller 中的模型除了 Id 字段之外的所有字段都为空,该字段似乎已自动神奇地填充。

在 View 中没有对应的“输入”元素的情况下,Id 字段如何以及在何处填充到模型中。

这可能是一个愚蠢的问题,但即使只是指向我应该阅读的内容的链接,我也会很感激。谢谢。

最佳答案

我打赌它来自作为路由参数的 url。

例如,您有以下 Controller :

public class HomeController: Controller
{
public ActionResult Index(int id)
{
vqr model = GetModel(id);
return View(model);
}

[HttpPost]
public ActionResult Index(MyViewModel model)
{
// the model.Id property will be automatically populated here
// because the request was POST /home/index/123
...
}
}

和以下 View :

@model MyViewModel
@using (Html.BeginForm())
{
<button type="submit">OK</button>
}

现在您导航到 GET /home/index/123 并获得以下标记:

<form action="/home/index/123" method="post">
<button type="submit">OK</button>
</form>

注意到表单的 action 属性了吗?这就是 id 的来源。基本上,Html.BeginForm() 帮助程序在生成 action 属性时使用当前 url,并且由于当前 url 是 /home/index/123,所以它就是被使用的。

并且因为如果您在 Global.asax 中保留了默认路由,则 {id} 路由 token 将用于 url 的末尾,默认模型绑定(bind)器会成功将其绑定(bind)到 Id View 模型的属性。

关于asp.net-mvc-3 - MVC 3 POST 数据和 Id 字段,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9566356/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com