Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Razor C# - Setting up checkbox values

I have my form with my checkbox inputs, and user can edit that. I can save these values in database good, but I don't know how to refill the form, so user can edit it.

This is my ViewBag var:

 ViewBag.NewFriends = preferences.NewFriends;// this value is a boolean, false

I try to pre-set values like this:

@using (Html.BeginForm("SavePreferences", "Conta"))
{
    @Html.HiddenFor(model => model.ID)
    @Html.CheckBox("newFriends", new { @checked = @ViewBag.NewFriends })
    @Html.Label("newFriends", "Solicitações de Amigo de Alma")
    <p><input type="submit" value="Send" /></p>
}

As HTML checkbox has the value checked="checked", and not true or false, it doesn't work. @Html.CheckBox has the first parameter as input name, and second a boolean checked(true or false).

My question is how can I easily set up this value? I tried:

@Html.CheckBox("newFriends", ViewBag.NewFriends) // where ViewBag.NewFriends = false

But it doesn't work at all...

Any idea?

like image 507
Rubia Gardini Avatar asked Sep 30 '11 06:09

Rubia Gardini


People also ask

What is Razor C#?

Razor is a markup syntax for embedding . NET based code into webpages. The Razor syntax consists of Razor markup, C#, and HTML. Files containing Razor generally have a . cshtml file extension.

What is Cshtml vs HTML?

Cshtml is basically razor view extension and any view renders in html finally. You need to use Razor in your application as it supports server side code but raw html does not.

What is the meaning of in Cshtml?

@ is used to switch from view markup to code.

What is difference between MVC and Razor pages?

A Razor Page is almost the same as ASP.NET MVC's view component. It has basically the syntax and functionality same as MVC. The basic difference between Razor pages and MVC is that the model and controller code is also added within the Razor Page itself. You do not need to add code separately.

What are Razor expression used for?

Razor provides expression encoding to avoid malicious code and security risks. In case, if user enters a malicious script as input, razor engine encode the script and render as HTML output.


1 Answers

Probably extension method CheckBox can't work with dynamic. I tried following example and it works:

@{ bool isNewFriends =  ViewBag.NewFriends; }
@Html.CheckBox("newFriends", isNewFriends);
like image 195
Samich Avatar answered Nov 13 '22 08:11

Samich