MVC3 passing base class to partial View - submitting form only has parent class values

丶灬走出姿态 提交于 2019-12-06 00:08:28

Unable to reproduce. Works fine for me. Notice that I am not using any constructors with my view models because the model binder wouldn't be able to call them and that all the properties must to have public getters and setters.

Model:

public abstract class BaseDetails
{
    public string Name { get; set; }
}

public class LocalDetails : BaseDetails
{
    public int Visits { get; set; }
}

Controller:

public class HomeController : Controller
{
    public ActionResult Index()
    {
        return View(new LocalDetails());
    }

    [HttpPost]
    public ActionResult Index(LocalDetails model)
    {
        return View(model);
    }
}

View (~/Views/Home/Index.cshtml):

@model LocalDetails
@using (Html.BeginForm())
{
    @Html.TextBoxFor(m => m.Visits)
    <br />
    @Html.Partial("Name", Model)
    <input type="submit" value="submit" />
}

Partial (~/Views/Home/Name.cshtml):

@model BaseDetails
@Html.TextBoxFor(x => x.Name)

When I submit the form inside the POST Index action both model properties Name and Visits are correctly bound with values from the form.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!