MyDaftQuestions
MyDaftQuestions

Reputation: 4701

How to make hiddenfor have value true

My form has to set a Boolean to true but, the user wont' be able to interact with the control to change this.

I think the best approach is to use the HiddenFor as it's not desirable to set this in the Controller for various reasons but I can't set the Boolean to true...

My code

            @using (Html.BeginForm())
            {
                @Html.LabelFor(mod => mod.EmailAddress)<br />
                @Html.TextBoxFor(mod => mod.EmailAddress)

                @Html.HiddenFor(mod => mod.IsSubsribed, new { value = true })
            }

I've tried

      @Html.HiddenFor(mod => mod.IsSubsribed, new { value = true })
      @Html.HiddenFor(mod => mod.IsSubsribed, new { value = "true" })
      @Html.HiddenFor(mod => mod.IsSubsribed, new { value = "checked" })

What do I need to do

Upvotes: 4

Views: 4995

Answers (2)

Aaron Hudon
Aaron Hudon

Reputation: 5839

When calling: @Html.HiddenFor(mod => mod.IsSubsribed)

If IsSubsribed is true, it will render:

<input type="hidden" name="IsSubsribed" value="true" />

If IsSubsribed is false, it will render:

<input type="hidden" name="IsSubsribed" value="false" />

If this is truly a parameter that cannot be modified by the user, a better convention is to use a hidden input that uniquely identifies the object being edited, and then perform sanity checks in the controller method given the primary key value.

Model

class MyModel
{
    public string PrimaryKey { get; set; }
    public string EmailAddress { get; set; }
}

View

@model MyModel
@using (Html.BeginForm())
{
    @Html.HiddenFor(m => m.PrimaryKey)
    @Html.TextBoxFor(m => m.EmailAddress)
    <button type="submit">Submit</button>
}

Controller

[HttpPost]
public ActionResult ProcessModel(MyModel model)
{
    if(ModelState.IsValid)
    {
        // lookup information based on model.PrimaryKey
        // process 'IsSubscribed...'
        // etc...

        // redirect to appropriate view
    }
    // invalid model state, return View for model
}

Upvotes: 0

Shyju
Shyju

Reputation: 218892

helper methods will ultimately render the input elements. So why not write an hidden input element tag ?

<input type="hidden" name="IsSubsribed" value="true" />

Or if you want to use the helper method, you can override the value explcititly (Usually the helper method use the value of the expression (your property))

@Html.HiddenFor(d=>d.IsSubsribed,new { Value="true"})

V in Value should be caps for this to work

But remember, user can still update this value and send it . So do not rely on values coming from client. If you know this should be always true, use true in your http post action method(server code) instead of relying on this value coming from client browser

In short, Do not blindly trust the data coming from client browser. It can be easily altered

Upvotes: 9

Related Questions