mvc中的模型绑定
我在表单中有一个文本框。
[视图]
<%=html.textbox("name") %>
[控制器]
Index(string name)
{
name = "something";
return View();
}
表单提交 在这种情况下,在不发送任何 ViewData 的情况下,文本框值将被保留。但值“something”未设置。
但是当我将操作更改为 [控制器]
Index()
{
string name="something";
return view();
}
该值不被维护。
该参数确实发生了变化。
i'm having a textbox inside a form.
[View]
<%=html.textbox("name") %>
[Controller]
Index(string name)
{
name = "something";
return View();
}
On Form Submit
In this case without sending any ViewData the textbox value is maintained.But the value "something" is not setting up.
But whn i change the Action to
[Controller]
Index()
{
string name="something";
return view();
}
the value is not maintained.
Really wat happening on that parameter.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
控制器中 Index 操作中的字符串名称映射到 FormValue,如果您更改此设置,MVC 会理解它需要将 FormValueCollection 中的值添加到文本框,并且您已在 Index 操作中更改了该值。如果您自己声明变量,则这不起作用,因为没有与表单值的绑定。
string name in your Index action in the controller, is mapped to the FormValue, if you change this, MVC understands that it needs to add the value from the FormValueCollection to the textbox, and you have changed that in your Index action. If you declare a variable by yourself this doesn't work because there is no binding to the formvalues.
如果要在控制器中设置 html.textbox("name") 的数据,请使用 ViewData["name"] = "something"
If you want to set data for html.textbox("name") in the Controller use ViewData["name"] = "something"
您的问题不是很清楚,您的代码示例实际上并未向 ViewData 或视图模型添加任何内容 - 这是我认为您尝试做的事情的一个镜头...
假设您想重新填充表单并且您的视图是强烈的输入后,您将执行以下操作:
视图中具有相同名称的文本框将从模型中自动填充值发布
表单然后将模型对象发布到您的控制器,如下所示:
然后重新填充表单与模型数据。
Your question is not very clear and your code example is not actually adding anything to ViewData or the view Model - here's a shot at what i think your trying to do...
Assuming you want to re-populate the form and your View is Strongly Typed, You would do something like this:
A textbox in your view with the same name would then have the value auto populated from the Model
Posting the form would then post the model object to your controller like this:
and then re-populate the form with the model data.