prepopulate Html.TextBoxFor在asp.net MVC 3 [英] prepopulate Html.TextBoxFor in asp.net mvc 3

查看:160
本文介绍了prepopulate Html.TextBoxFor在asp.net MVC 3的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

I'n在这个新的,所以道歉,如果这是不够的解释性的。我想prepopulate中的一个字段asp.net的MVC 3表单这工作;

I'n new at this, so apologies if this isn't explanatory enough. I want to prepopulate a field in a form in asp.net mvc 3. This works;

@Html.TextBox("CompName", null, new { @value = ViewBag.CompName })

但是,当我想用​​一个价值prepopulate它和值发送给我的模型,像这样的;

But when I want to prepopulate it with a value and send that value to my model, like this;

 @Html.TextBoxFor(model => model.Comps.CompName, null, new { @value = ViewBag.CompName })

这是行不通的。任何想法?

It won't work. Any ideas?

在此先感谢!

推荐答案

所以,我建议是将使用的ViewModels而不是ViewBag。我在我的项目叫的ViewModels发一个文件夹,然后在那里进行一些子文件夹宜于我把我的各种的ViewModels。

So, I would suggest is to move to using viewmodels rather than the ViewBag. I made a folder in my project called ViewModels and then under there make some subfolders as appropriate where I put my various viewmodels.

如果您创建一个视图模型类,像这样:

If you create a viewmodel class like so:

public class MyViewModel
{
   public string CompName { get; set; }
}

然后在您的控制器动作,您可以创建这些之一,并填充它,也许从一些现有型号从数据库中抽取。通过设置 COMPNAME 属性在视图模型,它会在你认为值。然后你的视图可以是这个样子:

then in your controller action you can create one of those and populate it, maybe from some existing model pulled from a database. By setting that CompName property in the viewmodel, it'll have that value in your view. And then your view can look something like this:

@model MyNamespace.ViewModels.MyViewModel

@Html.EditorFor(model => model.CompName)

@ Html.TextBoxFor 将工作太。

然后回到在后您的控制器动作,你已经得到的东西是这样的:

Then back in your controller action on the post, you've got something like this:

[HttpPost]
public ActionResult MyAction(MyViewModel viewModel)
{
   ...
   // do whatever you want with viewModel.CompName here, like persist it back
   // to the DB
   ...
}

可能是您使用类似automapper到您的模型和地图的ViewModels,但你当然可以这样做手工,以及,虽然整个左侧/右侧的事情变得相当繁琐。

Might be that you use something like automapper to map your models and viewmodels but you could certainly do that manually as well, though the whole lefthand/righthand thing gets quite tedious.

如果你做这种方式并没有太多的工作都使事情变得更加容易。

Makes things much easier if you do it this way and isn't much work at all.

更新

但是,如果你的真正的要传递的价值,鉴于ViewBag,你可以这样做:

But, if you really want to pass that value in view the ViewBag, you could do this:

在你的控制器动作:

ViewBag.CompName = "Some Name";

然后在您的视图:

Then in your view:

@Html.TextBoxFor(model =>model.Comps.CompName, new {@Value = ViewBag.CompName})

这将美元,有些名称P $ P-填充文本框。

And that'll pre-populate the textbox with "Some Name".

我还是会去的视图模型的方法,但这似乎工作不够好。希望帮助!

I'd still go with the viewmodel approach, but this seems to work well enough. Hope that helps!

这篇关于prepopulate Html.TextBoxFor在asp.net MVC 3的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆