2016-01-22 65 views
-1

我有一个非常简单的问题,可能有一个非常简单的答案,但是,我无法解决它。ASP.NET MVC从视图返回的空对象

我有如下视图模型:

namespace CommunicationsLog.ViewModels 
{ 
    public class CommunicationViewModel 
    { 
     public Communication Communication { get; set; } 
     public Feedback Feedback { get; set; } 
     public IEnumerable<Resolution> Resolutions { get; set; } 
    } 
} 

我试图从我的Add.cshtml页面创建一个沟通的新实例:

@model CommunicationsLog.ViewModels.CommunicationViewModel 
@{ 
    ViewBag.Title = "Add"; 
    Layout = "~/Views/Shared/_Layout.cshtml"; 
} 
@using (Html.BeginForm("Add", "Communication")) 
{ 
    <div class="form-horizontal" id="addForm"> 
     <div class="row"> 
      <div class="col-md-12"> 
       @Html.ValidationSummary(true, "", new { @class="text-danger"}) 
       <div class="form-group"> 
        @Html.LabelFor(model => model.Communication.Customer.Name, htmlAttributes: new { @class = "control-label col-md-2" }) 
        <div class="col-md-10"> 
         @if (Model.Communication.Customer.Name == null) 
         { 
          <input id="btnCust" type="button" value="Select Customer" class="btn btn-default addCustomer" /> 
         } 
         else 
         { 
          <span id="custSpan" style="font-size:16px; font:bold;"> 
           @Html.DisplayFor(model => model.Communication.Customer.Name) 
           <input id="btnEditCust" type="button" value="Edit" class="btn btn-default addCustomer"/> 
          </span> 
         } 
        <div id="addCust"></div> 
       </div> 
      </div> 
     </div> 
    <div class="form-group"> 
     <div class="col-md-offset-2 col-md-10"> 
      <input id="btnSubmit" type="submit" value="Create" class="btn btn-default" /> 
     </div> 
    </div> 
} 
<div> 
    @Html.ActionLink("Back to Communications", "Index") 
</div> 

在提交此调用下面控制器操作:

[HttpPost] 
    public ActionResult Add(CommunicationViewModel viewModel) 
    { 
     callEnd = DateTime.Now; 
     var totalCallTime = callEnd - callStart; 
     Communication insertedComm = null; 
     try 
     { 
      Communication comm = viewModel.Communication; 
      comm.CallTime = totalCallTime.ToString(@"mm\:ss"); 
      var customer = _uow.CustomerRepository.Get() 
               .Where(c => c.Name == comm.Customer.Name); 
      comm.CustomerId = customer.FirstOrDefault().CustomerId; 
      comm.Customer = customer.FirstOrDefault(); 
      comm.State = "Open"; 
      if (ModelState.IsValid) 
      { 
       insertedComm = _uow.CommunicationRepository.Insert(comm); 
       _uow.Save(); 

      } 

      Feedback feedback = viewModel.Feedback; 
      if (feedback.Type != null && feedback.Notes != null) 
      { 
       feedback.Communication = insertedComm; 
       feedback.CommunicationId = insertedComm.CommunicationId; 
       var insertedFB = _uow.FeedbackRepository.Insert(feedback); 
       _uow.Save(); 
      } 

      return RedirectToAction("Index"); 
     } 
     catch (Exception e) 
     { 
      if(viewModel.Communication == null) 
      { 
       viewModel.Communication = new Communication(); 
      }     
      return View(viewModel); 
     } 
    } 

但是,当viewModel加载到控制器操作时,通信对象为空。反馈对象已成功实例化。

调试后,我发现视图模型正确实例化,并且在页面加载时不为null,并且通过预定义的数据正确显示。它似乎只是失去了POST请求的价值。

任何人都可以帮忙吗?

非常感谢,

编辑:

正如指出的评论其实我已删除了我的片段,使这里的重要组成部分,是不包括JavaScript作为不相关的POST请求的完整视图:

@model CommunicationsLog.ViewModels.CommunicationViewModel 
@{ 
    ViewBag.Title = "Add"; 
    Layout = "~/Views/Shared/_Layout.cshtml"; 
} 
<h2>Add</h2> 
<link rel="stylesheet" href="//code.jquery.com/ui/1.11.4/themes/smoothness/jquery-ui.css"> 
<script src="//code.jquery.com/jquery-1.10.2.js"></script> 
<script src="//code.jquery.com/ui/1.11.4/jquery-ui.js"></script> 
@using (Html.BeginForm("Add", "Communication")) 
{ 
    <div class="form-horizontal" id="addForm"> 
     <h4>Communication</h4> 
     <div id="countdown" class="countdownHolder"></div> 
     <hr/> 
     <div class="row"> 
      <div class="col-md-12"> 
       @Html.ValidationSummary(true, "", new { @class="text-danger"}) 
       <div class="form-group"> 
        @Html.LabelFor(model => model.Communication.Customer.Name, htmlAttributes: new { @class = "control-label col-md-2" }) 
        <div class="col-md-10"> 
         @if (Model.Communication.Customer.Name == null) 
         { 
          <input id="btnCust" type="button" value="Select Customer" class="btn btn-default addCustomer" /> 
         } 
         else 
         { 
          <span id="custSpan" style="font-size:16px; font:bold;"> 
           @Html.DisplayFor(model => model.Communication.Customer.Name) 
           <input id="btnEditCust" type="button" value="Edit" class="btn btn-default addCustomer"/> 
          </span> 
         } 
         <div id="addCust"></div> 
        </div> 
       </div> 
       <div class="form-group"> 
        @Html.LabelFor(model => model.Communication.Receiver, htmlAttributes: new { @class = "control-label col-md-2" }) 
        <div class="col-md-10"> 
         @Html.EditorFor(model => model.Communication.Receiver, new { htmlAttributes = new { @class = "form-control" } }) 
         @Html.ValidationMessageFor(model => model.Communication.Receiver, "", new { @class = "text-danger" }) 
        </div> 
       </div> 
       <div class="form-group"> 
        @Html.LabelFor(model => model.Communication.Department, htmlAttributes: new { @class = "control-label col-md-2" }) 
        <div class="col-md-10"> 
         @Html.EditorFor(model => model.Communication.Department, new { htmlAttributes = new { @class = "form-control" } }) 
         @Html.ValidationMessageFor(model => model.Communication.Department, "", new { @class = "text-danger" }) 
        </div> 
       </div> 
       <div class="form-group"> 
        @Html.LabelFor(model => model.Communication.CommDateTime, htmlAttributes: new { @class = "control-label col-md-2" }) 
        <div class="col-md-10"> 
         <span id="custSpan" style="font-size:14px;"> 
          @Html.DisplayFor(model => model.Communication.CommDateTime) 
         </span> 
        </div> 
       </div> 
       <div class="form-group"> 
        @Html.LabelFor(model => model.Communication.Method, htmlAttributes: new { @class = "control-label col-md-2" }) 
        <div class="col-md-10"> 
         @Html.EditorFor(model => model.Communication.Method, new { htmlAttributes = new { @class = "form-control" } }) 
         @Html.ValidationMessageFor(model => model.Communication.Method, "", new { @class = "text-danger" }) 
        </div> 
       </div> 
       <div class="form-group"> 
        @Html.LabelFor(model => model.Communication.Product, htmlAttributes: new { @class = "control-label col-md-2" }) 
        <div class="col-md-10"> 
         @Html.EditorFor(model => model.Communication.Product, new { htmlAttributes = new { @class = "form-control" } }) 
         @Html.ValidationMessageFor(model => model.Communication.Product, "", new { @class = "text-danger" }) 
        </div> 
       </div> 
       <div class="form-group"> 
        @Html.LabelFor(model => model.Communication.PartNo, htmlAttributes: new { @class = "control-label col-md-2" }) 
        <div class="col-md-10"> 
         @Html.EditorFor(model => model.Communication.PartNo, new { htmlAttributes = new { @class = "form-control" } }) 
         @Html.ValidationMessageFor(model => model.Communication.PartNo, "", new { @class = "text-danger" }) 
        </div> 
       </div> 
       <div class="form-group"> 
        @Html.LabelFor(model => model.Communication.Description, htmlAttributes: new { @class = "control-label col-md-2" }) 
        <div class="col-md-10"> 
         @Html.EditorFor(model => model.Communication.Description, new { htmlAttributes = new { @class = "form-control" } }) 
         @Html.ValidationMessageFor(model => model.Communication.Description, "", new { @class = "text-danger" }) 
        </div> 
       </div> 
       <div class="form-group"> 
        @Html.Label("Feedback?", htmlAttributes: new { @class = "control-label col-md-2" }) 
        <div class="col-md-10"> 
         <input type="checkbox" id="chkFeedback" name="chkFeedback" onclick="showFeedbackForm(this)"/> 
        </div> 
       </div> 
       <div id="feedbackForm" style="display:none"> 
        <div class="form-group"> 
         @Html.LabelFor(model => model.Feedback.Type, htmlAttributes: new { @class = "control-label col-md-2" }) 
         <div class="col-md-10"> 
          @Html.EditorFor(model => model.Feedback.Type, new { htmlAttributes = new { @class = "form-control" } }) 
          @Html.ValidationMessageFor(model => model.Feedback.Type, "", new { @class = "text-danger" }) 
         </div> 
        </div> 
        <div class="form-group"> 
         @Html.LabelFor(model => model.Feedback.Notes, htmlAttributes: new { @class = "control-label col-md-2" }) 
         <div class="col-md-10"> 
          @Html.EditorFor(model => model.Feedback.Notes, new { htmlAttributes = new { @class = "form-control" } }) 
          @Html.ValidationMessageFor(model => model.Feedback.Notes, "", new { @class = "text-danger" }) 
         </div> 
        </div> 
       </div> 
      </div> 
     </div> 
    </div> 
    <div class="form-group"> 
     <div class="col-md-offset-2 col-md-10"> 
      <input id="btnSubmit" type="submit" value="Create" class="btn btn-default" /> 
     </div> 
    </div> 
} 
<div> 
    @Html.ActionLink("Back to Communications", "Index") 
</div> 

我不知道是否有帮助,但这里是从VS全堆栈跟踪:

Object reference not set to an instance of an object.  
    at ASP._Page_Views_Communication_Add_cshtml.Execute() in C:\Projects\CommunicationsLog\CommunicationsLog\Views\Communication\Add.cshtml:line 24 
    at System.Web.WebPages.WebPageBase.ExecutePageHierarchy() 
    at System.Web.Mvc.WebViewPage.ExecutePageHierarchy() 
    at System.Web.WebPages.StartPage.RunPage() 
    at System.Web.WebPages.StartPage.ExecutePageHierarchy() 
    at System.Web.WebPages.WebPageBase.ExecutePageHierarchy(WebPageContext pageContext, TextWriter writer, WebPageRenderingBase startPage) 
    at System.Web.Mvc.RazorView.RenderView(ViewContext viewContext, TextWriter writer, Object instance) 
    at System.Web.Mvc.BuildManagerCompiledView.Render(ViewContext viewContext, TextWriter writer) 
    at System.Web.Mvc.ViewResultBase.ExecuteResult(ControllerContext context) 
    at System.Web.Mvc.ControllerActionInvoker.InvokeActionResult(ControllerContext controllerContext, ActionResult actionResult) 
    at System.Web.Mvc.ControllerActionInvoker.InvokeActionResultFilterRecursive(IList`1 filters, Int32 filterIndex, ResultExecutingContext preContext, ControllerContext controllerContext, ActionResult actionResult) 
    at System.Web.Mvc.ControllerActionInvoker.InvokeActionResultFilterRecursive(IList`1 filters, Int32 filterIndex, ResultExecutingContext preContext, ControllerContext controllerContext, ActionResult actionResult) 
+0

由于MVC无法找到任何要绑定的东西,因此您没有约束任何东西。我看到displayfor和labels,但你的输入在哪里? – Chad

+0

抱歉,我已经更新了我的问题全景 – DaRoGa

+0

如果删除@ Html.HiddenFor(model => model.Communication),会发生什么情况? –

回答

1

由于您使用的标记,任何<input>标签都需要有一个名字定义的输入名称/值对被回传到服务器:

<input name="@Html.NameFor(i => i.Communication.Customer.Name)" ... /> 

然后模型将被填充。您还可以使用:

@Html.TextBoxFor(i => i.Communication.Customer.Name) 

所有的输入都需要这个。我也看到你的价值属性包含“选择客户”;这将回发到服务器。如果使用placeholder="Select Customer",则此值不会发布到服务器,但仍会在文本框为空时显示。

+0

工作方式是,如果没有客户进行通信,那么只会显示一个按钮,它将加载一个对话框,供您选择一个客户,然后重新加载具有正确详细信息的添加视图(这一切都有效)客户被选中,然后它在显示器上显示该名称并显示编辑按钮。所以你可以澄清哪些输入我需要改变,以及如何在当前,客户名称显示为不是在输入。对不起,如果我失去了一些东西,而且很天真 – DaRoGa

+0

@DaRoGa你不是天真的;你在这里有一个复杂的设置。我真的不知道我的理解足够引导你。但是你必须理解MVC模型绑定数据的规则。所以它使用了一个通过使用Html.NameFor(i => i.Communication.Customer.Name)助手将输入的名称映射到模型的约定,该助手为客户端生成了类似Communcation__Customer__Name的东西(这不是100%正确的... ),所以MVC然后使用这个约定来重新绑定一个嵌套模型。 MVC没有看到任何这样的输入返回到服务器,因此您的模型为空。 –

+0

你的挑战是弄清楚什么你需要发送到服务器何时何地,在形式....我注意到没有你的标签没有名称属性,所以当一个职位发生时,什么都不是通过POST操作发送到服务器.... –