1

I am trying out an ASP.Net MVC application, and I am looking into ways to set default values through the controller.

For example, using the following model:

public class MyItem
{
    public int ID { get; set; }
    public int ItemTypeID { get; set; }
    public string Description { get; set; }
    public DateTime CreateDate { get; set; }
}

I have figured out how to set values in the HttpPost Create function (such as type and create date, whose values won't be visible or editable to the user).

public class MyItemsController : Controller
{

    ...

    [HttpPost]
    [ValidateAntiForgeryToken]
    public ActionResult Create(
        [Bind(Include = "ID,ItemTypeID,Description,CreateDate")] MyItem myItem)
    {
        if (ModelState.IsValid)
        {
            // Set values for behind-the-scenes columns.
            myItem.ItemTypeID = 1;
            myItem.CreateDate = DateTime.Now;

            db.MyItems.Add(myItem);
            db.SaveChanges();
            return RedirectToAction("Index");
        }

        return View(myItem);
    }

    ...

}

The problem with this, however, is that it doesn't execute until the user clicks the Save button. There are times when I would like to have an initial value set when the Save view first appears. In this example, maybe I want the description to have a default value including a date:

myItem.Description = string.Format("Item Created on {0:MM/dd/yyyy}", DateTime.Today);

I would like the text box on the Create view to default to this value when the user first enters, but they could type something different.

What would be the best way to set an initial value for the Create views?

1
  • 1
    You would set these values in your Get Action for the Create form. What does your get for the form look like? Commented Sep 22, 2017 at 17:20

1 Answer 1

3

With your GET action just modify your model:

public ActionResult Create()
{
    var myItem = new myItem();

    myItem.Description = string.Format("Item Created on {0:MM/dd/yyyy}", DateTime.Today);

    return View(myItem);
}
Sign up to request clarification or add additional context in comments.

3 Comments

I made this change, and worked for the Description. Thanks. I also moved the assignment of ItemTypeID to the Get Create, but when I got to Post, it was set to 0 again. As I mentioned, the user won't see type, so I took its text box off of the view. Will I need to leave it on as a hidden field?
Yea, you could use a hidden field for that.
The value did carry over when I added @Html.HiddenFor(model => model.ItemTypeID, null) to my Create.cshtml file.

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.