-1

I am using MVC Entity framework i have generated code i have fields Isactive this fields have values true or false . code looks like

controller:

 [HttpPost]
        [ValidateAntiForgeryToken]
        public ActionResult Edit([Bind(Include="ClientId,ClientName,PrimaryContactName,EmailId,PrimaryContact,IsActive,ModifiedBy,ParentCompany")] TP_InternalClients tP_InternalClients)
        {
            if (ModelState.IsValid)
            {
                db.Entry(tP_InternalClients).State = EntityState.Modified;
                db.SaveChanges();
                return RedirectToAction("Index");
            }
            return View(tP_InternalClients);
        }

model:

 public class InternalClients
    {
        public int ClientId { get; set; }
        public string ClientName { get; set; }
        public string PrimaryContactName { get; set; }
        public string EmailID { get; set; }
        public string PrimaryContact { get; set; }
        public bool IsActive { get; set; }
        public string ModifiedBy { get; set; }
        public int ParentCompany { get; set; }
    }

View:

 <div class="col-md-10">
                <div class="checkbox">
                    @Html.EditorFor(model => model.IsActive)
                    @Html.ValidationMessageFor(model => model.IsActive, "", new { @class = "text-danger" })
                </div>
            </div>

after run the code Isactive drop down showing true or false i want hidden field that time send value default true only to database . how i can hidden and send value default ? i doing i am getting error

thenna
  • 423
  • 1
  • 5
  • 26

1 Answers1

1

In your form , simply replace

<div class="checkbox">
     @Html.EditorFor(model => model.IsActive)
     @Html.ValidationMessageFor(model => model.IsActive, "", new { @class = "text-danger" })
</div>

with

<input type="hidden" name="IsActive" value="true" />

Or you can use the Html helper method

@Html.HiddenFor(s=>s.IsActive)

Now make sure you set the default value to whatever you want in the GET action.

But, If you want a default value to be saved, Do it in your HttpPost action, No need to keep the Hidden field in the form (Users can update the hidden field value using browser dev tools)

[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult Edit([Bind(Include="ClientId,ClientName,PrimaryContactName,EmailId,
                       PrimaryContact,ModifiedBy,ParentCompany")] TP_InternalClients model)
{
        if (ModelState.IsValid)
        {
            model.IsAcive = true ; 
            db.Entry(model).State = EntityState.Modified;
            db.SaveChanges();
            return RedirectToAction("Index");
        }
        return View(tP_InternalClients);
}

Remember, the best way to prevent overposting is to use a view model with only those properties needed for the view.

Community
  • 1
  • 1
Shyju
  • 214,206
  • 104
  • 411
  • 497