In this session of ASP.NET Core Tutorial we will introduce EditorForModel HTML Helper and also talk about HiddenInput attribute. EditorForModel helper, helps us to create Edit Form for connected Model to the View. Moreover we can hide properties of the model in Edit Form with HiddenInput attribute.
Create Edit Form with EditorForModel in MVC
As above mentioned, we can create Edit Form with this BeginForm and EditorForModel helper for the connected model to the view. Thus, in this project, for creating Edit form for Cost module, first we need to create an Action Method with HTTPGET attribute inside CostController. Also, we need to get record data which we can catch it with GetCostByID method in Cost repository that we created in previous sessions. Then, we can pass the data to the View which we will create for editing Cost record data.
1 2 3 4 5 6 7 8 9 10 |
[HttpGet] public IActionResult Edit(int id) { var SelectCost = costRepository.GetCostByID(id); return View(SelectCost); } |
Next, we need a View that should be created in Views/Cost path. After that, we should bind the View to Cost Model with Model directive. Then, we can create Edit Form with BeginForm and EditorForModel html helper.
1 2 3 4 5 6 7 8 9 10 11 12 13 |
@model Cost @{ ViewBag.Title = "Edit Cost Record"; } @using (Html.BeginForm()) { @Html.EditorForModel() <br /> <button type="submit">Save</button> } |
Hide Model Property with HiddenInput attribute
If we compile and run our project after above steps, we can see all the properties of Cost Model are available for editing purpose. While, sometimes one or some of the properties should be hidden and we should prevent user to change them. Same as ID in this model that contains unique and key value for this entity. Thus, we should hide this property in editing mode. For this purpose we can use HiddenInuet attribute in Cost Model. this attribute is in Microsoft.AspNetCore.Mvc namespace that should be added to Cost class.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 |
public class Cost { [HiddenInput(DisplayValue =false)] public int ID { get; set; } public decimal Amount { get; set; } public DateTime Date { get; set; } public string Comment { get; set; } public string Category { get; set; } public int PaymentMethod { set; get; } } |
As you can see in above code we use [HiddenInput(DisplayValue =false)] for hiding ID property in edit form.
If you need more details, watch this session video. Also, for being updated about our coming sessions, follow us on Instagram, Facebook, Telegram or YouTube. Also you can have access to list of all sessions HERE.
You can download this Session Slides form HERE