Binding Hidden fields in core mvc c# entity-framework-core


I am writting an application with core 2.0 mvc.

Here is one of my controller's action:

    public async Task<IActionResult> MyAction(long id, [Bind("id_person,name")] Person p)
        ViewBag.message = "";
        if ( == "")
            ViewBag.message = "You need to set name.";
        else if (ModelState.IsValid == false)
            ViewBag.message = string.Join("; ", ModelState.Values.SelectMany(x => x.Errors).Select(x => x.ErrorMessage));
            await mydb_context.SaveChangesAsync();
            return RedirectToAction(nameof(Index));
        return View(p);

And here is the associated cshtml razor view:

@model myproject.Person

<form asp-action="MyAction">
    <input type="hidden" asp-for="id_person" />
    <input asp-for="name" />
    <input type="submit">

Everything works fine: This action works great for insert and updating Persons.

Now, let's suppose i have a third field in my Person entity. For example "age".

I want this field to be secret. That's mean i do not want to user to see this information in his browser. I do not want too to put this information in an hidden field because the user may see or change the information.

My problem is if i keep MyAction and cshtml view as is, the age is set to null when a user updates a person. I want the age to keep its actual value in database.

Is there a basic way to do this ? I do not want to set by hand getters and setters in MyAction method, because i have a lot of fields. I want to work with Binding.


12/14/2017 3:19:17 PM

Popular Answer

I don't know if it's still available in EFCore but I used to do this in EF6.

If you only want to update the Name propoerty, you can use mydb_context.Entry().

var person = mydb_context.Person.FirstOrDefault(p => p.id_person == id);

if(person != null)
      mydb_context.Entry(person).Property("name").CurrentValue = "Toto";

Read this for more details

3/26/2019 10:18:59 AM

Related Questions


Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow
Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow