简体   繁体   中英

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

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.

需要指出的另一件事是,如果要传递存储在web.config文件中的键值(例如reCAPTCHA),并且验证失败,则还需要在HttpPost部分中设置键值。

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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