简体   繁体   English

为什么在调用视图时,视图中的嵌套对象为null。 ASP.Net MVC

[英]Why nested objects in view are null when calling the view. ASP.Net MVC

I'm new to MVC and I'm struggling deeply with this behaviour: 我是MVC的新手,我正在努力解决这个问题:

When I want to save with the Edit method (POST) I make some validations and when an error occurs I call again the view and I send the same object. 当我想使用Edit方法(POST)进行保存时,我进行了一些验证,当发生错误时,我再次调用视图并发送相同的对象。 However in the view all the inner objects are null. 但是在视图中,所有内部对象都为null。

Here is an example: 这是一个例子:

public class Product 
{
  public int Id { get; set; }
  public string Name { get; set; }
  public DateTime ExpirationDate { get; set; }
  public int CategoryId { get; set; }
  public virtual Category Category { get; set; }
}

public class Category 
{
  public int CategoryId { get; set; }
  public string Name { get; set; }
}

My controller is this: 我的控制器是这样的:

[HttpPost]
public ActionResult Edit(Product product, string submitButton)
{
  if(submitButton == "Save")
  {
    if (ModelState.IsValid)
    {
        db.Entry(product).State = EntityState.Modified;
        db.SaveChanges();
        return RedirectToAction("Index");
    }
  }
  else // Validate
  {
    if(product.Expiration <= DateTime.Now)
    {
      ViewBag.Message "Product is expired";
      return View(product); // In the view the object property 'Category' is null. Why?
    }
  }
}

Update. 更新。 Here's the view. 这是观点。

@model sgt.Models.Product

@{
    ViewBag.Title = "Edit Product";
}

<h2>Edit</h2>

@using (Html.BeginForm())
{
    @Html.AntiForgeryToken()

    <div class="form-horizontal">
        <h4>Product</h4>
        <hr />
        @Html.ValidationSummary(true, "", new { @class = "text-danger" })
        @Html.HiddenFor(model => model.Id)

        <div class="form-group">
            @Html.LabelFor(model => model.Name, htmlAttributes: new { @class = "control-label col-md-2" })
            <div class="col-md-10">
                @Html.EditorFor(model => model.Name, new { htmlAttributes = new { @class = "form-control" } })
                @Html.ValidationMessageFor(model => model.Name, "", new { @class = "text-danger" })
                <input type="submit" value="Validate" class="btn btn-default" />
            </div>
        </div>

        <div class="form-group">
            @Html.LabelFor(model => model.ExpirationDate, htmlAttributes: new { @class = "control-label col-md-2" })
            <div class="col-md-10">
                @Html.EditorFor(model => model.ExpirationDate, new { htmlAttributes = new { @class = "form-control" } })
                @Html.ValidationMessageFor(model => model.ExpirationDate, "", new { @class = "text-danger" })
                <input type="submit" value="Validate" class="btn btn-default" />
            </div>
        </div>

        <div class="form-group">
            @Html.LabelFor(model => model.Category, htmlAttributes: new { @class = "control-label col-md-2" })
            <div class="col-md-10">
                @Html.DisplayFor(model => model.Category.Name, new { htmlAttributes = new { @class = "form-control" } })
            </div>
        </div>

        <div class="form-group">
            <div class="col-md-offset-2 col-md-10">
                <input type="submit" value="Save" class="btn btn-default" />
            </div>
        </div>
    </div>
}

<div>
    @Html.ActionLink("Return", "Index")
</div>

@section Scripts {
    @Scripts.Render("~/bundles/jqueryval")
}

Thanks in advance 提前致谢

YOu have a logical Error in your code. 你的代码中有一个逻辑错误。

You are not returning the View if (ModelState.IsValid) Fails 如果(ModelState.IsValid)失败,则不返回View

[HttpPost]
public ActionResult Edit(Product product, string submitButton)
{
    if(submitButton == "Save")
    {
        if (ModelState.IsValid)
        {
            db.Entry(product).State = EntityState.Modified;
            db.SaveChanges();
            return RedirectToAction("Index");
        }

        // Here RETURN VIEW and MODEL

        return View(product);
    }
    else // Validate
    {
        if(product.Expiration <= DateTime.Now)
        {
        ViewBag.Message "Product is expired";
        return View(product); // In the view the object property 'Category' is null. Why?
        }

        // ALSO HERE YOU ARE NOT RETURNING A VIEW AND MODEL

        return View(product);
    }
}

Just wondering, but I think you want to check if Model is Valid AND product.Expiration <= DateTime.Now 只是想知道,但我想你想检查Model is Valid product.Expiration <= DateTime.Now

[HttpPost]
public ActionResult Edit(Product product, string submitButton)
{
      if(product.Expiration <= DateTime.Now && submitButton != "Save"){
         ModelState.AddModelError("Expiration", "Product is expired");
       }


       if (ModelState.IsValid)
       {
           db.Entry(product).State = EntityState.Modified;
           db.SaveChanges();
           return RedirectToAction("Index");
        }
        return View(product);
}

EDIT: TRY THIS: 编辑:尝试这个:

   [HttpPost]
   public ActionResult Edit(Product product, string submitButton)
   {
    if(submitButton == "Save")
    {
            if (ModelState.IsValid)
            {
                db.Entry(product).State = EntityState.Modified;
                db.SaveChanges();
                return RedirectToAction("Index");
            }
            return View(product);
    }
       if(product.Expiration <= DateTime.Now)
       {
           ViewBag.Message "Product is expired";
       }
       return View(product);
   }

EDIT YOUR VIEW: 编辑你的观点:

<div class="form-group">
    @Html.HiddenFor(m => m.Category.CategoryId)
    @Html.HiddenFor(m => m.Category.Name )

    @Html.LabelFor(model => model.Category, htmlAttributes: new { @class = "control-label col-md-2" })
    <div class="col-md-10">
        @Html.DisplayFor(model => model.Category.Name, new { htmlAttributes = new { @class = "form-control" } })
    </div>
</div>      

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 在视图中的模型内调用模型。 (asp.net MVC) - Calling a model within a model in a view. (asp.net MVC) 当我模拟ASP.NET MVC控制器时,我的ActionMethod不返回任何视图。 为什么? - When I mock my ASP.NET MVC controller, my ActionMethod returns no view. Why? ASP.Net MVC仪表板视图。 在哪里执行汇总 - ASP.Net MVC Dashboard View. Where to perform aggregations ASP.NET MVC无法将数据和相关数据发送到视图。 (查看模型模式?) - ASP.NET MVC Trouble getting data and related data to the view. (View Model Pattern?) Asp.Net MVC-视图-&gt;创建2个对象 - Asp.Net MVC - View -> Create 2 objects 如何在视图中渲染图像。 图片的值= byte []。 ASP.NET MVC - how to render image in view. value of image = byte[]. asp.net mvc ASP.Net MVC ViewBag 在视图中不起作用。 ViewBag 结果正确 - ASP.Net MVC ViewBag is not working in View. ViewBag result is Correct 默认登录asp.net MVC3重定向到错误的视图。 这个在哪里? - Default Login asp.net MVC3 redirect to wrong view. Where is this set? ASP.NET MVC 如何从嵌套对象的视图模型集合中动态创建表结构 - ASP.NET MVC How to create table structure dynamically in view from viewmodel collection of nested objects ASP.NET MVC结构。 从视图中调用控制器 - ASP.NET MVC Structure. calling a controller from a view
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM