2

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?

2
  • I might be misunderstanding you but why not just delete the above code from your view and set CreatedAt in the method? Commented Oct 19, 2011 at 14:22
  • On your controller you have a method to handle the get request which renders the view. You should also have a method on the controller, usualy called the same name but with an attribute of httppost. This handles the page when its submited, so set the value in this method. Commented Oct 19, 2011 at 14:32

1 Answer 1

2

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:

 @Html.HiddenFor(m => m.CreatedAt, DateTime.Now);

Then when the model is POSTed to the controller, the CreatedAt property 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

[HttpPost]
public ActionResult Edit(Product product)
{
    product.CreatedAt // should equal the DateTime.Now set when you created the View
}

}

or you could set it in the controller after it POSTs:

public class MyController : Controller { //other stuff

[HttpPost]
public ActionResult Edit(Product product)
{
    product.CreatedAt = DateTime.Now;
}

}

You may run into issues with Html.Hidden in this context, if you do, make sure to use the work around in place.

Sign up to request clarification or add additional context in comments.

1 Comment

@Hotcoder what's the action it POSTs to look like? What do your routes look like?

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.