简体   繁体   English

提交表单,返回对象的初始化,而不是null mvc C#

[英]Submit the form return the initialization of the object instead of null mvc C#

[HttpPost]    
public async Task<ActionResult> Create(BookingViewModel bookingview, BookingDetailsViewModel bookingdetails)

I am having a problem that when I submit the form I am expecting that the bookingdetails is null if I didn't show its PartialView related to it 我遇到一个问题,当我提交表单时,如果我不显示与其相关的PartialView ,则期望bookingdetails为null

@if (Model.StepNumber == (int)Booking_Steps.BookingDetails)
 {
   @Html.Partial("_Booking_Details", Model.BookingDetails)
 }

but instead it initialize the object. 但是它初始化对象。 How to make it return null? 如何使其返回null? because that's make the ModelState not valid. 因为那会使ModelState无效。

I believe the model binder initializes objects to check their ModelState, although I could be mistaken. 我相信模型绑定器会初始化对象以检查其ModelState,尽管我可能会误会。

A quick fix you could do is add a hidden field in the if block and check it in your action. 您可以做的快速修复是在if块中添加一个隐藏字段,并在操作中进行检查。

@if (Model.StepNumber == (int)Booking_Steps.BookingDetails)
{
  <input type="hidden" name="partialRenderedFlag" value="true" />
  @Html.Partial("_Booking_Details", Model.BookingDetails)
}

Controller action: 控制器动作:

public async Task<ActionResult> Create(BookingViewModel bookingview, BookingDetailsViewModel bookingdetails, bool partialRenderedFlag = false)
{
  if (partialRenderedFlag)
    // you know you rendered partial
}

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

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM