ASP.NET 从视图中返回的 MVC 空对象

本文关键字:MVC 对象 返回 NET 视图 ASP | 更新日期: 2023-09-27 18:31:25

我有一个非常简单的问题,可能有一个非常简单的答案,但是,我无法解决。

我有一个视图模型如下:

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);
        }
    }

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

调试后,我发现视图模型已正确实例化,并且在页面加载时不为空,并且由正确显示的预定义数据显示。它似乎只丢失了 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)

ASP.NET 从视图中返回的 MVC 空对象

由于您使用的是标记,因此任何<input>标记都需要定义名称,因此输入的名称/值对将回发到服务器:

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

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

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

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