I created my first MVC application in ASP.NET today. I have a datetime column “CreatedAt” which should be filled by current date without being visible in the input form. But the generated code has this code:
<div class="editor-field">
@Html.EditorFor(model => model.CreatedAt)
@Html.ValidationMessageFor(model => model.CreatedAt)
</div>
It displays a textbox in input form. I don’t want to display it, instead it should be set in code behind. How can I do that?
ASP.NET MVC doesn’t have a concept of a ‘code-behind’. Quite simply, you send data from your View, and it’s processed in your Controller.
So if this is an action that POSTs, then we can send data back to the controller, and even better, we can keep that data ‘hidden’ from the textbox view.
In your view, you should replace that with the following line:
Then when the model is POSTed to the controller, the
CreatedAtproperty will have the DateTime.Now filled in.When you POST something, it has to go to an Action Method:
public class MyController : Controller
{
//other stuff
}
or you could set it in the controller after it
POSTs:public class MyController : Controller
{
//other stuff
}
You may run into issues with
Html.Hiddenin this context, if you do, make sure to use the work around in place.