Display a formatted date in a TextBoxFor() in Asp .Net MVC

In ASP.NET MVC, you can display a formatted date in a TextBoxFor using the DisplayFormat attribute on your model property and the @Html.TextBoxFor HTML helper. Here's how you can do it step by step:

  1. Define a model with a property for the date:
public class MyModel
{
    [Display(Name = "Date")]
    [DisplayFormat(DataFormatString = "{0:yyyy-MM-dd}", ApplyFormatInEditMode = true)]
    public DateTime MyDate { get; set; }
}

In this example, the DisplayFormat attribute is used to specify the format of the date. The DataFormatString property is set to "yyyy-MM-dd", which will format the date as "YYYY-MM-DD".

  1. In your controller, create an instance of the model and pass it to the view:
public ActionResult Index()
{
    MyModel model = new MyModel
    {
        MyDate = DateTime.Now
    };
    return View(model);
}
  1. In your view, use @Html.TextBoxFor to create an editable text box for the date property:
@model MyModel
@using (Html.BeginForm())
{
    <div class="form-group">
        @Html.LabelFor(model => model.MyDate)
        @Html.TextBoxFor(model => model.MyDate, new { @class = "form-control" })
        @Html.ValidationMessageFor(model => model.MyDate)
    </div>
    
    <input type="submit" value="Submit" class="btn btn-primary" />
}

In this code, we're using @Html.TextBoxFor to generate an input element for the MyDate property. The new { @class = "form-control" } part is for adding CSS classes if you want to style the text box.

  1. Make sure you have the necessary validation scripts and styles included in your layout or view for client-side validation to work correctly.

That's it! Now, when you load the page, the date in the TextBoxFor will be displayed in the specified format ("YYYY-MM-DD" in this case), and you can edit it. When you submit the form, ASP.NET MVC will automatically bind the edited date to the model property.

 
About Us | Terms of Use | Privacy Policy | Disclaimer | Contact Us Copyright © 2012-2024 CodingFusion
50+ C# Programs for beginners to practice