1

I am building a little CRUD application in ASP.NET MVC5. Instead of a own model I am using the autogenerated models of EF. The table (named "tablex") accessed by EF has a DateTime value (named "inserted").

Controller:

// Show edit
public async Task<ActionResult> Edit(int? id)
{
    tablex x = await db.tablex.FindAsync(id);
    return View(x);
}

// Edit
public async Task<ActionResult> Edit([Bind(Include = "id,...,updated")] tablex x)
{
    if (ModelState.IsValid)
    {
        x.inserted = DateTime.Now;
        db.Entry(x).State = EntityState.Modified;
        await db.SaveChangesAsync();
        return RedirectToAction("Index");
    }
    return View(x);
}

This is my shortened Controller. As you can see I override my DateTime field anyway.

View:

@model DatabaseEF.Models.tablex
@using (Html.BeginForm())
{
    <div....> //more fields
    <div ...>
        @Html.Label("Inserted ", ...)
        <div ...>
            @Html.EditorFor(model => model.inserted, ...)
            @Html.ValidationMessageFor(model => model.inserted, "", ...)
        </div>
        <input type="submit" value="Save" ... />
    </div>
}

With this my EditorFor-Textbox shows the date like "28.05.2015 17:12:17" (German format). When pressing "Save" the view warns that the field mus be a date. Changing the value to e.g. "2010-10-10" works perfectly.

Now I found some solutions with annotations to the model "DataType(DataType.Date)]". But as my model is autogenerated by the EF I'm looking for a working solution.

Anybody with help for me out there?

Stix
  • 455
  • 5
  • 16
  • 1
    Have you considered using view models for the round-trip between the browser and the server, then validating those and mapping back to a domain model when saving to the database? This will give you full control over how the view interacts with the models. – tvanfosson May 29 '15 at 13:42
  • yes, you need to have control of the attributes, so create an in-between view model. you'll need to do this a lot as many of your views will not be 1-1 with your database, and *shouldn't* be. – DLeh May 29 '15 at 13:44
  • Sorry for that late reply. There was a way for adding annotations to the Database first EF model: http://stackoverflow.com/questions/16736494/add-data-annotations-to-a-class-generated-by-entity-framework That's how I added the DataType, which worked out quite easy. Thanks for your answers. – Stix Jun 05 '15 at 13:29

0 Answers0