Yantup
Yantup

Reputation: 72

How to set a default value for a hidden field?

im working in a project that creates 2 types of users: admin and member. To differenciate them i have set a bool value, true => admin || false => member.

Only admins can create admins, if an anon user tries to create an account, the default value for that field needs to be false. I have set a @html.HiddenFor in that field, but its sending a null value so the model can't be saved in the database.

this is the code:

[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult Registro(
        [Bind(Include="Id,Login,Pass,Nombre,Apellido,Rol")]Usuario objUser)
{
    //somecode

    var errors = ModelState.Values.SelectMany(v => v.Errors);
    //error shows the null 'rol' parameter
    if (ModelState.IsValid)
    {
        db.Usuario.Add(objUser);
        db.SaveChanges();
        return RedirectToAction("Login");
    }

    return View(objUser);
}

Razor:

@using (Html.BeginForm())
{
    @Html.AntiForgeryToken()
    @Html.HiddenFor(model => model.Rol)

    //some inputs for the other fields
}

Haven't found info related to that is it possible or do i need to do something else?

Upvotes: 0

Views: 3618

Answers (1)

MBARK T3STO
MBARK T3STO

Reputation: 339

i suggest you to use this simple way :

you can using viewbag to do this .

In Controller :

viewbag.Test="This is a test";

In View :

  <input type="hidden" id="Test" name="Test" value="@Viewbag.Test">

Upvotes: 3

Related Questions