ASP.NET MVC中如何确保构造函数设置的StartTime在表单提交时传递?
StartTime Value from ViewModel Constructor on Form Submission Got it, let's break this down. The core issue here is how ASP.NET MVC's model binding behaves during form submission: when you post the form, the framework will create a new instance of your AdvertisementViewModel (triggering the constructor again, which sets StartTime to the current time at submission—not the initial time when the form was loaded). To keep the original StartTime value you set when the form first loaded, you need to include that value in the data sent back to the controller.
Here are the most straightforward and reliable solutions:
1. Use a Hidden Input Field (Recommended)
The simplest way is to render your StartTime property as a hidden field in the form. This way, the initial value set in the constructor gets written to the HTML, and is sent back to the controller when the form is submitted.
In your Razor view, add this line alongside your other form fields:
@model AdvertisementViewModel @using (Html.BeginForm("SaveAdvertisement", "Advertisement", FormMethod.Post)) { <!-- Your other form fields go here --> @* Render the initial StartTime as a hidden field *@ @Html.HiddenFor(m => m.StartTime) <button type="submit">Save Advertisement</button> }
ASP.NET MVC's HiddenFor helper automatically handles date formatting, so the value will be serialized correctly into the hidden input. When the form is submitted, the model binder will use this posted value instead of the one set by the newly instantiated ViewModel's constructor.
2. Initialize StartTime in the GET Action (Alternative Approach)
Instead of setting StartTime in the ViewModel's constructor, you can initialize it directly in the GET action that serves the form. This makes the flow more explicit, and you still use a hidden field to preserve the value:
Controller GET Action:
public ActionResult CreateAdvertisement() { var viewModel = new AdvertisementViewModel(); viewModel.StartTime = DateTime.Now; // Set initial time here instead of constructor return View(viewModel); }
Then use the same HiddenFor code in the view as above. This approach is useful if you ever need to adjust the initial StartTime logic without modifying the ViewModel itself.
Important Notes:
- Security Consideration: If preventing users from tampering with the
StartTimevalue is critical, you should validate the value on the server side (e.g., check that it's within a reasonable window of the current time) or encrypt the hidden field value. - Date Formatting: The
HiddenForhelper handles date serialization correctly for model binding, but avoid manually formatting the date unless you're sure the model binder can parse it.
内容的提问来源于stack exchange,提问作者user9610034

