Gisiota
Gisiota

Reputation: 343

Passing value from Controller to View in MVC

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

Answers (2)

J Weezy
J Weezy

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

Stuart
Stuart

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

Related Questions