简体   繁体   中英

How to pass parameter from query string from view to controller

While in Create View I have this link: http://localhost:17697/Reports/Create?personId=2 .

Inside a view I have a form:

@using (Html.BeginForm()) {
    @Html.AntiForgeryToken()

    <div class="form-horizontal">

        <hr />
        @Html.ValidationSummary(true, "", new { @class = "text-danger" })
        @Html.HiddenFor(model => model.Id)

        <div class="form-group">
            @Html.LabelFor(model => model.Text, htmlAttributes: new { @class = "control-label col-md-2" })
            <div class="col-md-10">
                @Html.EditorFor(model => model.Text, new { htmlAttributes = new { @class = "form-control" } })
                @Html.ValidationMessageFor(model => model.Text, "", new { @class = "text-danger" })
            </div>
        </div>

        <div class="form-group">
            <div class="col-md-offset-0 col-md-10">
                <input type="submit" value="Save" class="btn btn-success" style="width: 200px; font-weight: bold;" />
            </div>
        </div>
    </div>

When I click Save button I submit the form and invoke POST Create action method. I would also pass there this 2 from ?personId=2 in query string from link inside a view to POST Create method.

 [HttpPost]
        [ValidateAntiForgeryToken]
        public ActionResult Create([Bind(Include = "Id,Text")] Report report) {
            // I WANT TO GET personId=2 from query string here
            if (ModelState.IsValid) {
                db.Reports.Add(report);
                db.SaveChanges();
                return RedirectToAction("Index");
            }
            return View(report);
        }

Will adding this inside a form is correct approach? @Html.Hidden( @Html.Encode("personId"))

Add it as a parameter...

public ActionResult Create([Bind(Include = "Id,Text")] Report report, int personId){
}

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