Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

prepopulate Html.TextBoxFor in 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 })

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?

Thanks in advance!

like image 489
Dan Avatar asked Sep 07 '11 16:09

Dan


2 Answers

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; }
}

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)

or @Html.TextBoxFor would work too.

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
   ...
}

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.


Update

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

In your controller action:

ViewBag.CompName = "Some Name";

Then in your view:

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

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!

like image 84
itsmatt Avatar answered Nov 19 '22 16:11

itsmatt


From your controller, if you pass a model initialized with default values using one of the View(...) method overloads that accepts a model object, these values will be used by the view when rendered. You won't need to use the @value = ... syntax.

like image 45
sellmeadog Avatar answered Nov 19 '22 18:11

sellmeadog