简体   繁体   中英

ASP.Net MVC Initial Values on Create

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?

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);
}

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