简体   繁体   中英

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

@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? because that's make the ModelState not valid.

I believe the model binder initializes objects to check their ModelState, although I could be mistaken.

A quick fix you could do is add a hidden field in the if block and check it in your action.

@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
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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