简体   繁体   English

MVC中的模型绑定

[英]model binding in mvc

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. 在表单提交时,在这种情况下,不发送任何ViewData,将保留文本框值。但是未设置值“ something”。

But whn i change the Action to [Controller] 但是当我将动作更改为[Controller]时

Index()
{
string name="something";
return view();
}

the value is not maintained. 该值不保留。

Really wat happening on that parameter. 真正发生在该参数上的水。

如果要在Controller中为html.textbox(“ name”)设置数据,请使用ViewData [“ name”] =“ something”

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... 您的问题不是很清楚,您的代码示例实际上并未在ViewData或View Model中添加任何内容-这是我认为您尝试执行的操作的镜头...

Assuming you want to re-populate the form and your View is Strongly Typed, You would do something like this: 假设您要重新填充表单,并且您的视图是强类型的,则可以执行以下操作:

public ActionResult Index(String name)
{
    MyModel model = new MyModel;
    model.Name = name;
    ViewData.Model = model;
    return View();
}

A textbox in your view with the same name would then have the value auto populated from the Model 视图中具有相同名称的文本框将具有从模型自动填充的值

<%= html.textbox("Name") %>

Posting the form would then post the model object to your controller like this: 发布表单将把模型对象发布到您的控制器,如下所示:

[AcceptVerbs(HttpVerbs.Post)]
public ActionResult Index(MyModel model)
{
    // do something with the model        
    ViewData.Model = model;
    return View();
}

and then re-populate the form with the model data. 然后使用模型数据重新填充表单。

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. 控制器中Index动作中的字符串名称已映射到FormValue,如果更改此名称,则MVC理解它需要将FormValueCollection中的值添加到文本框中,并且已在Index动作中进行了更改。 If you declare a variable by yourself this doesn't work because there is no binding to the formvalues. 如果您自己声明变量,那么这将无效,因为没有绑定到formvalues。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM