基类中的属性未出现在视图模型中

ser*_*gpa 3 c# asp.net-mvc asp.net-mvc-5

我有一个看起来像这样的基类:

public class EformBase
{
    public decimal Latitude { get; set; }
    public decimal Longitude {get;set;}
    // lots of other properties here
}
Run Code Online (Sandbox Code Playgroud)

和一个看起来像这样的派生类:

public class GraffitiViewModel : EformBase
{
    public RadioButtonList<YesNoType> GraffitiOffensive { get; set; }
    public RadioButtonList<YesNoType> GraffitiTag { get; set; }
    // other properties here
}
Run Code Online (Sandbox Code Playgroud)

我在MVC中使用此类作为视图模型.不幸的是,当回发视图模型时,基类中的属性不会出现在视图模型中.像这样:

[HttpPost]
public ActionResult Index(GraffitiViewModel vm)
{
   // add to database code
}
Run Code Online (Sandbox Code Playgroud)

当回发到此操作时,vm不包括基类中指定的经度和纬度.我错过了什么?我是否必须为基类做一些特殊的事情?

Vli*_*nce 5

不幸的是,您的帖子没有提及您是否(或不)使用视图中的两个属性(纬度和经度).

此外,当您提到: 不幸的是,当回发视图模型时,基类中的属性不会出现在视图模型中.

你的意思是你没有看到这两个属性?

要么

你的意思是你看到两个属性,但值是null?

请考虑以下代码示例:

ViewModel和Base类:

public class MyViewModel : MyBaseViewModel
{
    public string A { get; set; }
    public string B { get; set; }
    public string C { get; set; }
    public string D { get; set; }
}

public class MyBaseViewModel
{
    public string Z { get; set; }
}
Run Code Online (Sandbox Code Playgroud)

控制者:

public class HomeController : Controller
{
    public ActionResult Index()
    {
        var model = new MyViewModel();
        return View(model);
    }

    [HttpPost]
    public ActionResult Index(MyViewModel myViewModel)
    {
        var z = myViewModel.Z;
        return null;
    }
}
Run Code Online (Sandbox Code Playgroud)

风景:

@model MvcApplication1.Models.MyViewModel

@using (Html.BeginForm()) {
    <fieldset>
        <legend>MyViewModel</legend>
        <div class="editor-label">@Html.LabelFor(model => model.A)</div>
        <div class="editor-field">@Html.EditorFor(model => model.A)</div>

        <div class="editor-label">@Html.LabelFor(model => model.B)</div>
        <div class="editor-field">@Html.EditorFor(model => model.B)</div>

        <p><input type="submit" value="Create" /></p>
    </fieldset>
}
Run Code Online (Sandbox Code Playgroud)

请注意视图仅仅使用属性A和属性B.

当我<form>在Controller中的[HttpPost]方法上提交并设置断点时,我可以查看为文本框A和文本框B输入的值.

但由于我没有文本框C和文本框D.这些属性将设置为null.

同样,属性Z恰好在我的Base类中定义.

因为我没有使用属性Z <form>,所以当我提交它时,我将null作为值.

要在提交时查看属性Z <form>,您必须将其添加到您的内容中<form>...</form>,以便:

<div class="editor-label">@Html.LabelFor(model => model.Z)</div>
<div class="editor-field">@Html.EditorFor(model => model.Z)</div>
Run Code Online (Sandbox Code Playgroud)