I have a schema ( table saved in Sql) like this:
ID | Name | Address
1 Sam ADD1
2 John ADD2
3 Tony ADD3
I have three fields in my form - ID , Name and Address
.
Now I have implemented a drop-down for the ID field using ViewBag
to pass data between the view and the controller.
I want to set the value of the fields Name and Address
using the ID selected from the drop-down and not manually but I am unable to figure out a way and tried searching but could not find any appropriate solution.
Thanks for the Help.
EDIT:
My Code So Far:
Model Has been generated using the table itself (Database First Approach)
Controller
public ActionResult Create()
{
ViewBag.codes = db.Users.ToList();
return View();
}
[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult Create(Entity_Master entity_Master)
{
if (ModelState.IsValid)
{
db.Entity_Master.Add(entity_Master);
db.SaveChanges();
return RedirectToAction("Index");
}
ViewBag.codes = db.Users.ToList();
return View(entity_Master);
}
View
@Html.LabelFor(model => model.ID, htmlAttributes: new { @class = "control-label col-md-2" })
@Html.DropDownListFor(model => model.ID, new SelectList(ViewBag.codes, "ID", "ID", "Select ID"))
@Html.ValidationMessageFor(model => model.ID, "", new { @class = "text-danger" })
@Html.LabelFor(model => model.Name, htmlAttributes: new { @class = "control-label col-md-2" })
@Html.EditorFor(model => model.Name, new { htmlAttributes = new { @class = "form-control" } })
@Html.ValidationMessageFor(model => model.Name, "", new { @class = "text-danger" })
@Html.LabelFor(model => model.Address, htmlAttributes: new { @class = "control-label col-md-2" })
@Html.EditorFor(model => model.Address, new { htmlAttributes = new { @class = "form-control" } })
@Html.ValidationMessageFor(model => model.Address, "", new { @class = "text-danger" })
Rendered Html
<select id="ID" name="ID">
<option value="1">1</option>
<option value="2">2</option>
<option value="3">3</option>
<option value="4">4</option>
<option value="5">5</option>
</select>
<input class="form-control text-box single-line" id="Name" name="Name" type="text" value="" />
<span class="field-validation-valid text-danger" data-valmsg-for="Name" data-valmsg-replace="true"></span>
<input class="form-control text-box single-line" id="Address" name="Address" type="text" value="" />
<span class="field-validation-valid text-danger" data-valmsg-for="Address" data-valmsg-replace="true"></span>