控制器无法访问子模型 post

Controller cannot access Child Model post

我有一个实例化 2 个子模型的 MVC 模型。

public class SModel
{
    public Pl sv = new Pl();
    public SLinks sm = new SLinks ();
}

当我在 razor 视图中显示数据时,一切正常:

@Html.DisplayFor(model => model.sv.ListOfCategories.First().Description, new { @class = "body" })

但是当我 post 返回到控制器时,"All" 值为空或 0。

Razor 中的文本框:

@Html.TextBoxFor(model => model.sm.YXZLink, new { @class = "post-input", @maxlength = "500" })

进入:

  [HttpPost]
    [ValidateAntiForgeryToken]
    public ActionResult xxx(SModel model)

model.sm.YXZLink

不仅此值为空或 0,所有其他值也为空或 0。

控制器可以访问子模型中的值吗? 如果我能够显示子模型,我应该能够访问 post.

上的子值

SModel class 仅包含字段。 DefaultModelBinder 无法绑定到字段。而是通过添加 getters 和 setters

将它们更改为属性
public class SModel
{
  public Pl sv { get; set; }
  public SLinks sm { get; set }
}

然后在无参数构造函数中初始化每个类型的新实例,或者在控制器的 GET 方法中赋值。

使用下面的代码格式,

型号:

public class masterModel
    {
        public childModelFirst childModelFirstEntity { get; set; }
        public childModelSecond childModelSecondEntity { get; set; }
    }    
    public class childModelFirst
    {
        public string Code { get; set; }
    }
    public class childModelSecond
    {
        public string Code { get; set; }
    }

查看:

@using (Ajax.BeginForm("About", "Home", new AjaxOptions { HttpMethod="POST",InsertionMode = InsertionMode.Replace,UpdateTargetId="target" }))
    {
        @Html.EditorFor(model=>model.childModelFirstEntity.Code)
        @Html.EditorFor(model => model.childModelSecondEntity.Code)

        <input type="submit" value="Add" />
    }

控制器:

public ActionResult About()
    {
        ViewBag.Message = "Your app description page.";

        var mastermdl = new masterModel();
        mastermdl.childModelFirstEntity = new childModelFirst();
        mastermdl.childModelSecondEntity = new childModelSecond();
        mastermdl.childModelFirstEntity.Code = "001";
        mastermdl.childModelSecondEntity.Code = "002";
        return View(mastermdl);
    }
    [HttpPost]
    public ActionResult About(masterModel model)
    {
        model.childModelFirstEntity.Code = model.childModelSecondEntity.Code;
        return View();
    }