Binding Hidden fields in asp.net core mvc

asp.net-core-mvc c# entity-framework-core

Question

I am writting an application with asp.net core 2.0 mvc.

Here is one of my controller's action:

    [HttpPost]
    public async Task<IActionResult> MyAction(long id, [Bind("id_person,name")] Person p)
    {
        ViewBag.message = "";
        if (p.name == "")
        {
            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));
        }
        else
        {
            mydb_context.Update(p);
            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">
    <div>@ViewBag.message</div>
    <input type="hidden" asp-for="id_person" />
    <input asp-for="name" />
    <input type="submit">
</form>

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.

Thanks

1
0
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";
      mydb_context.SaveChanges();
}

Read this for more details https://docs.microsoft.com/fr-fr/ef/ef6/saving/change-tracking/property-values

0
3/26/2019 10:18:59 AM


Related Questions





Related

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