Binding an InputCheckBox to an Integer Model field

Posted 3 years ago by mgp
Edited 3 years ago
0

Hi, I need a lot of help, lol. But I hope I can get an answer for this one question.

I have a Blazor App Solution which has a model defined in the Shared project. The model has an integer field named 'Active'.

In my razor page EditForm I am trying to bind an InputCheckbox to the field. Obviously the data types of boolean and int are different.

How would you go about updating the record's 'Active' field from a checkbox. I am open to using js but was wondering if I am just missing some simple understanding.

I was also considering using a hidden InputNumber bound to the "Active' field, and change the value of that based on the changed event of a html checkbox.

I'm getting a little confused as to the correct way of doing this. I welcome any help or insight you have to offer.

Thanks

  • 1

    I'm sure you've already considered it, but my first thought would be to switch the type of the property in the model to be a boolean.

    Otherwise, inside the @code block, maybe you could add a property for the boolean, set it inside OnInitializedAsync based on the value of "Active", and assign the proper value to your "Active" property in the method that fires on a valid submit. If boolean is true, Active = 1, else 0.

    The general idea is something like (I haven't tested this):

    <EditForm Model="@_myModel" OnValidSubmit="SubmittingForm">
    	<InputCheckbox @bind-Value="_active" />
    	<button type="submit">Submit</button>
    </EditForm>
    
    @code {
    	private bool _active { get; set; }
    	private MyModel _myModel = new MyModel();
    	
    	protected override async Task OnInitializedAsync()
    	{
    		_myModel = await //... get your model data from the controller
    		
    		if(_myModel.Active == 1)
    			_active = true;
    		else
    			_active = false;
    	}
    	
    	private void SubmittingForm()
    	{
    		// Set the value of the Active property with the value of _active
    		if(_active == true)
    			_myModel.Active = 1;
    		else
    			_myModel.Active = 0;
    			
    		//continue...
    	}
    }
    Posted 3 years ago by selliott Edited 3 years ago
  • 0

    Yep Thats a good idea. The Status field in the database is an int. So your solution maybe just what I need. However while working on this problem, I started getting 403s out of the blue on authorized pages, so now I am fighting that. But that is another topic. Thanks for your input! If I ever get authorization solid I will implement your idea.

    Posted 3 years ago by mgp
Someone is typing...

Post a Reply

You must be logged in to add a new post.
Number of online users: 0
An error has occurred. This application may no longer respond until reloaded. Reload 🗙