Reputation: 343
I have a view that was generated using data scaffolding. The view has a textfield:
Create View:
<div class="form-group">
@Html.LabelFor(model => model.GroupId, htmlAttributes: new { @class = "control-label col-md-2" })
<div class="col-md-10">
@Html.EditorFor(model => model.GroupId, new { htmlAttributes = new { @class = "form-control" } })
@Html.ValidationMessageFor(model => model.GroupId, "", new { @class = "text-danger" })
</div>
</div>
I'd like to pass a value from a controller to this textfield. And I did the following, which doesn't seem to work.
Controller:
public ActionResult Create(int id)
{
ViewBag.GroupId = id;
Debug.WriteLine("DEBUG: "+id);
return View();
}
Upvotes: 2
Views: 29591
Reputation: 3935
One additional thing to point out is that if you are passing a key value that is stored in the web.config file, say for reCAPTCHA, and the validation fails then you will need to also set the key value in the HttpPost section.
Upvotes: 0
Reputation: 764
You could do this by using the ViewBag
to store GroupId
as you currently are, but as your view is using a model, it may be better to go that way instead.
So you would have:
Model:
public class GroupModel
{
public int GroupId { get; set; }
}
Controller:
public ActionResult Create(int id)
{
var model = new GroupModel();
model.GroupId = id
return View(model);
}
At the top of your view, you would then reference your model:
@model GroupModel
You can then access the model in the view using code like model.GroupId
as per the scaffolding has done.
Upvotes: 6