0

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"))

2
  • Why woudln't you just have the person id as a property of the model? Commented Sep 20, 2014 at 17:54
  • get personid in post controller as public ActionResult Create([Bind(Include = "Id,Text")] Report report,int?personId) Commented Sep 20, 2014 at 17:55

1 Answer 1

2

Add it as a parameter...

public ActionResult Create([Bind(Include = "Id,Text")] Report report, int personId){
}
Sign up to request clarification or add additional context in comments.

2 Comments

So I do not have to @Html.Encode inside a form and hide it?
It did work. I wanted to do it hard way to insert this data into ViewData and forgot about basics.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.