2

I'm using an autogenerated form from visual studio for asp.net mvc 5 that saves information to a database. It's the create view with the standard scaffolding etc from asp.net with entity framework.

I like the way the form looks, but I need one field (datecreated) to at least be auto filled, (but preferably autofilled and hidden). The problem is I don't understand the autogenerated code at all and my efforts to look it up have not been successful. Nor have my efforts to understand it. I'm still a beginner with html helpers, which I think these are.

Here is the form element I am working with. The part in the middle is the part I need to change to autofill (the date created field), I think the relevant part is changing the EditorFor. but I don't know:

@using (Html.BeginForm())
{
@Html.AntiForgeryToken()


            <div class="form-horizontal">
                <h4>New Patient:</h4>
                <hr />
                @Html.ValidationSummary(true, "", new { @class = "text-danger" })

... //other form items removed for simplicity

    <div class="form-group">
        @Html.LabelFor(model => model.DateCreated,"Date Created", htmlAttributes: new { @class = "control-label col-md-2" })
        <div class="col-md-10">
            @Html.EditorFor(model => model.DateCreated, new { htmlAttributes = new { @class = "form-control" } })
            @Html.ValidationMessageFor(model => model.DateCreated, "", new { @class = "text-danger" })
        </div>
    </div>

... //more items left out for simplicity

    <div class="form-group">
        <div class="col-md-offset-2 col-md-10">
            <input type="submit" value="Create" class="btn btn-default" />
        </div>
    </div>
}

And the auto generated controller for this part looks like this:

// GET: Subjects/Create
    public ActionResult Create()
    {
        return View();
    }

    // POST: Subjects/Create
    // To protect from overposting attacks, please enable the specific properties you want to bind to, for 
    // more details see http://go.microsoft.com/fwlink/?LinkId=317598.
    [HttpPost]
    [ValidateAntiForgeryToken]
    public ActionResult Create([Bind(Include = "ID,Name,DOB,Male,Female,Address,City,ZIP,PhoneHome,PhoneCell,Email,EmergencyContact,EmergencyContactPhone,EmergencyContactRelationship,ReferredBy,DateCreated,Allergy,AllergyDescription,HighBloodPressure,LowBloodPressure,HeartCondition,Diabetes,Anemia,HighCholesterol,Pacemaker,Epilepsy,Pregnant,Cancer,STD,Pain,PainDescription,Headache,HeadacheDescription,CommonCold,HighBloodPressureConcern,Stress,Depression,Sleep,Menstruation,Fertility,WeightControl,Other")] Subject subject)
    {
        if (ModelState.IsValid)
        {
            db.SubjectDatabase.Add(subject);
            db.SaveChanges();
            return RedirectToAction("Index");
        }

        return View(subject);
    }

If you dont know how I can autofill and or hide the form element datecreated, could you please point me to where I might learn to figure this out myself. I think I am reasonable at programming, I just don't understand html helpers well, or the bind function in the controller.

3
  • 2
    A DateCreated field should never be in a form used for creating data. You set that value in the POST method immediately before saving the object to the data base. And do not use data models in your view - create a view model - refer What is ViewModel in MVC? Commented Feb 4, 2017 at 20:54
  • 1
    That's right, just remove the entire <div class="form-group"> containing the @Html.EditorFor(model => model.DateCreated, and do this inside your action like this: model.DateCreated = DateTime.Now. Commented Feb 4, 2017 at 21:10
  • Ok. Thanks for clarifying how to do this. I was confused because it was like two things i didnt understand very well interacting with each other, and I didn't want to break something. I'll add the assignment in the method. Thanks Commented Feb 5, 2017 at 8:10

2 Answers 2

2

Remove this part from your View

 <div class="form-group">
        @Html.LabelFor(model => model.DateCreated,"Date Created", htmlAttributes: new { @class = "control-label col-md-2" })
        <div class="col-md-10">
            @Html.EditorFor(model => model.DateCreated, new { htmlAttributes = new { @class = "form-control" } })
            @Html.ValidationMessageFor(model => model.DateCreated, "", new { @class = "text-danger" })
        </div>
    </div>

And then, inside your Controller remove DateCreated from Bind attribute and assign DateCreated property:

    [HttpPost]
    [ValidateAntiForgeryToken]
    public ActionResult Create([Bind(Include = "ID,Name,DOB,Male,Female,Address,City,ZIP,PhoneHome,PhoneCell,Email,EmergencyContact,EmergencyContactPhone,EmergencyContactRelationship,ReferredBy,Allergy,AllergyDescription,HighBloodPressure,LowBloodPressure,HeartCondition,Diabetes,Anemia,HighCholesterol,Pacemaker,Epilepsy,Pregnant,Cancer,STD,Pain,PainDescription,Headache,HeadacheDescription,CommonCold,HighBloodPressureConcern,Stress,Depression,Sleep,Menstruation,Fertility,WeightControl,Other")] Subject subject)
    {
        if (ModelState.IsValid)
        {
            subject.DateCreated = DateTime.Now; //if you want UTC time, use DateTime.UtcNow
            db.SubjectDatabase.Add(subject);
            db.SaveChanges();
            return RedirectToAction("Index");
        }

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

Comments

1

The @Value can also be used to prefill in spots by using @Html.EditorFor:

Example:

@Html.EditorFor(c => c.Propertyname, new { @Value = "5" })

There is more information to be found at: Html.EditorFor Set Default Value

Comments

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.