1

There is something simple I don't understand with ChildActions.

I've created a simple View for a model, that loads a child action with a form. The child action has another model than its parent, with a different id property.

Html.HiddenFor(m => m.Id) still outputs the parents id, although @Model.id outputs the correct value!

Can't I reliably use the Helper methods in ChildActions, or is this a known bug?

HomeController

public class HomeController : Controller
{
    public ActionResult Index()
    {
        var model = new Models.HomeModel { id = 1, message = "bugmodel" };
        return View(model);
    }

    [HttpGet]
    [ChildActionOnly]
    public ActionResult Child(int id)
    {
        var model = new Models.HomeChildModel { id = 100, parentId = id, childMessage = "My Child message" };
        return PartialView(model);
    }

    [HttpPost]
    [ActionName("Child")]
    [ValidateAntiForgeryToken()]
    public ActionResult ChildPost(Models.HomeChildModel model)
    {
        return RedirectToAction("Index");
    }
}

Models

public class HomeModel
{
    public int id { get; set; }
    public string message { get; set; }
}

public class HomeChildModel
{
    public int id { get; set; }
    public int parentId { get; set; }
    public string childMessage { get; set; }
}

Home view

@model ChildActionBug.Models.HomeModel
@{
    ViewBag.Title = "Index";
}

<h2>Index</h2>
@Html.DisplayFor(m=>m.id)
@Html.DisplayFor(m=>m.message)

@Html.Action("Child", new { id = Model.id })

**Child view**

@model ChildActionBug.Models.HomeChildModel
<h3>Child here</h3>
@using (Html.BeginForm())
{
    @Html.AntiForgeryToken()
    @Html.HiddenFor(m=>m.id)
    @Html.HiddenFor(m=>m.parentId)
    @Html.EditorFor(m=>m.childMessage)

    <div>Child Model ID: @Model.id</div>
    <button type="submit">Save</button>
}
Jason Evans
  • 28,906
  • 14
  • 90
  • 154
Mattias Åslund
  • 3,877
  • 2
  • 18
  • 17
  • This might be a good reference for you: http://stackoverflow.com/questions/4710447/asp-net-mvc-html-hiddenfor-with-wrong-value – Jason Evans May 02 '14 at 10:47

1 Answers1

2

Based on the answer given in the SO question I posted in the comment, you're better off explicitly creating the hidden fields

ASP.Net MVC Html.HiddenFor with wrong value

That's normal and it is how HTML helpers work. They first use the value of the POST request and after that the value in the model. This means that even if you modify the value of the model in your controller action if there is the same variable in the POST request your modification will be ignored and the POSTed value will be used.

So instead, hand craft the hidden fields:

<input type="hidden" name="Id" value="@Model.Id" />
<input type="hidden" name="ParentId" value="@Model.ParentId" />
<input type="hidden" name="ChildMessage" value="@Model.ChildMessage" />
Community
  • 1
  • 1
Jason Evans
  • 28,906
  • 14
  • 90
  • 154