Tyler Sigi Tyler Sigi - 4 years ago 281
ASP.NET (C#) Question

How to auto fill fields in a form using @Html.EditorFor in ASP.net MVC 5?

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.

Answer Source

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);
    }
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download