GilliVilla
GilliVilla

Reputation: 5090

In MVC 5 - How to compare 2 boolean values and set it as a third booelan in View?

I have

View

@Html.HiddenFor(x => Model.IsPersistable})

Model

public class MyModel()
{
  public bool IsPersistable{ get; set; }
  public bool StoreAsIndiv {get;set;}
  public bool StoreAsOrg {get;set;}
}

I have 2 check boxes in the view mapping to StoreAsIndiv and StoreAsOrg. If either of them are selected I wanted to assign true to IsPersistable which is a hidden field.

How to accomplish this?

EDIT/Update: I want to avoid any Javascript if possible

Upvotes: 0

Views: 525

Answers (4)

Federico Alecci
Federico Alecci

Reputation: 914

Just change your model to this:

public class MyModel()
{
  public bool IsPersistable{ get { return StorageAsIndiv || StorageAsOrg; }
  public bool StoreAsIndiv {get;set;}
  public bool StoreAsOrg {get;set;}
}

If IsPersistable is a field you will use on the controller, you don't need javascript. If you are planning to manipulate the dom based on it's value, you will have to use some as @Christos suggested above.

Upvotes: 1

Jasen
Jasen

Reputation: 14250

If the user can alter the values but not affect IsPersistable then

@model MyModel
@{
    Model.IsPersistable = Model.StoreAsIndiv || Model.StoreAsOrg;
}

@Html.HiddenFor(x => Model.IsPersistable)

The HiddenFor() will pickup the value you set earlier.

Upvotes: 1

Usman
Usman

Reputation: 4703

if you say that the value of IsPersistable will only be set at view render then you can try something like that

 @Html.HiddenFor(x => x.IsPersistable, new { Value = Model.StoreAsIndiv || Model.StoreAsOrg })

or if you want to change the value in model @Jasen's answer is best

Upvotes: 1

Christos
Christos

Reputation: 53958

You could try the following:

$(function(){
    var isPersistableEle = $("#IsPersistable");
    var storeAsIndivEle = $("#StoreAsIndiv");
    var storeAsOrgEle = $("#StoreAsOrg");

    function checkUncheckIsPersistable(){
        if(storeAsIndivEle.is(':checked') 
           && storeAsOrgEle.is(':checked')){
            isPersistableEle.prop('checked', true); 
        } else {
            isPersistableEle.prop('checked', false); 
        }
    }

    storeAsIndivEle.on("change", function(){
        checkUncheckIsPersistable();
    });

    storeAsOrgEle.on("change", function(){
        checkUncheckIsPersistable();
    })  
});

Upvotes: 1

Related Questions