我在Controller-View-Controller的方式上丢失了数据。如何从View中获取模型?

时间:2018-01-26 21:44:55

标签: c# .net asp.net-mvc

我有一个包含少数属性的Model。有List<Point>ThranslatingCamThranslatingCam包含应由用户输入的属性。

public class TranslatingCamModel
{
   public TranslatingCam Cam { get; set; }
   public List<Point> Points { get; set; }
}

现在我只使用Points进行可视化,但将来此列表将由用户更改。

在Controller中,我初始化Points列表,将其添加到我的TranslatingCamModel并将其发送到视图。

public ActionResult Cam()
{
   TranslatingCamModel model = new TranslatingCamModel();
   List<Points> points = new List<Points>();

   //here I add same data to the points list

   model.Points = points;
   model.Cam = new TranslatingCam();

   return View("TranslatingCam", model);
}

此代码可以按我的意思运行。我的问题更进一步。

@model CamShaft.WebUI.Models.TranslatingCamModel

@{
    ViewBag.Title = "Cam";
}

<div class="prop">
    @using (Html.BeginForm("DrawTranslatingCam", "Home"))
    {
      @Html.LabelFor(model => model.Cam.Rmin, htmlAttributes: new { @class = "control-label col-md-2" })
      @Html.EditorFor(model => model.Cam.Rmin, new { htmlAttributes = new { @class = "form-control" } })
      //And the same for the other Cam's properties
      <input type="submit" value="Draw" />
    }
</div>
//Here is my code for visualization and etc... And here I can work with the model.Points. 

它运作正常,我获得Cam的价值,但我丢失了Points列表。

public ActionResult DrawTranslatingCam(TranslatingCamModel model)
{
    //Here I have model returned from the View
}

以下是用户数据输入的model.Cam,但model.Points列表为null。但是在我将它发送到视图之前我已将其初始化..

我尝试使用@Html.HiddenFor来解决:

@using (Html.BeginForm("DrawTranslatingCam", "Home"))
{
    @Html.LabelFor(model => model.Cam.Rmin, htmlAttributes: new { @class = "control-label col-md-2" })
    @Html.EditorFor(model => model.Cam.Rmin, new { htmlAttributes = new { @class = "form-control" } })
    //And the same for the other Cam's properties

    @Html.HiddenFor(model => model.Points)
    <input type="submit" value="Draw" />
    } 

在这种情况下返回Points列表,但没有日期(不是null,只有count = 0)

那么,我如何才能从视图中获取我的模型?

为了紧凑和清晰,代码略有修改。

0 个答案:

没有答案