how to set radio button checked in edit mode in MVC razor view - asp.net-mvc-4

I am new in MVC razor. I am trying to edit the web page. In which I have two radio buttons. I am successful in save data for radio button values. But when I trying to edit that value I am not able to select that radio button for which data is saved.
I have enum for Gender
public enum Gender
{
Male,
Female
}
My create code is :-
<div class="editor-label">
#Html.LabelFor(model => model.gender)
</div>
<div class="editor-field">
#Html.RadioButtonFor(x => x.gender, (int)Gender.Male) Male
#Html.RadioButtonFor(x => x.gender, (int)Gender.Female) Female
</div>
Edit code is like
<div class="editor-label">
#Html.LabelFor(model => model.gender)
</div>
<div>
#if (Model.gender == (int)Gender.Male)
{
#Html.RadioButtonFor(model => model.gender, "Male", new { #checked = true })
#Html.Label("Male")
#Html.RadioButtonFor(model => model.gender, "Female")
#Html.Label("Female")
}
else
{
#Html.RadioButtonFor(model => model.gender, "Male")
#Html.Label("Male")
#Html.RadioButtonFor(model => model.gender, "Female", new { #checked = true })
#Html.Label("Female")
}
</div>

You have written like
#Html.RadioButtonFor(model => model.gender, "Male", new { #checked = true }) and
#Html.RadioButtonFor(model => model.gender, "Female", new { #checked = true })
Here you have taken gender as a Enum type and you have written the value for the radio button as a string type- change "Male" to 0 and "Female" to 1.

Don't do this at the view level. Just set the default value to the property in your view model's constructor. Clean and simple. In your post-backs, your selected value will automatically populate the correct selection.
For example
public class MyViewModel
{
public MyViewModel()
{
Gender = "Male";
}
}
<table>
<tr>
<td><label>#Html.RadioButtonFor(i => i.Gender, "Male")Male</label></td>
<td><label>#Html.RadioButtonFor(i => i.Gender, "Female")Female</label></td>
</tr>
</table>

Here is the code for get value of checked radio button and set radio button checked according to it's value in edit form:
Controller:
[HttpPost]
public ActionResult Create(FormCollection collection)
{
try
{
CommonServiceReference.tbl_user user = new CommonServiceReference.tbl_user();
user.user_gender = collection["rdbtnGender"];
return RedirectToAction("Index");
}
catch(Exception e)
{
throw e;
}
}
public ActionResult Edit(int id)
{
CommonServiceReference.ViewUserGroup user = clientObj.getUserById(id);
ViewBag.UserObj = user;
return View();
}
VIEW:
Create:
<input type="radio" id="rdbtnGender1" name="rdbtnGender" value="Male" required>
<label for="rdbtnGender1">MALE</label>
<input type="radio" id="rdbtnGender2" name="rdbtnGender" value="Female" required>
<label for="rdbtnGender2">FEMALE</label>
Edit:
<input type="radio" id="rdbtnGender1" name="rdbtnGender" value="Male" #(ViewBag.UserObj.user_gender == "Male" ? "checked='true'" : "") required>
<label for="rdbtnGender1">MALE</label>
<input type="radio" id="rdbtnGender2" name="rdbtnGender" value="Female" #(ViewBag.UserObj.user_gender == "Female" ? "checked='true'" : "") required>
<label for="rdbtnGender2">FEMALE</label>

Here is how I do it and works both for create and edit:
//How to do it with enums
<div class="editor-field">
#Html.RadioButtonFor(x => x.gender, (int)Gender.Male) Male
#Html.RadioButtonFor(x => x.gender, (int)Gender.Female) Female
</div>
//And with Booleans
<div class="editor-field">
#Html.RadioButtonFor(x => x.IsMale, true) Male
#Html.RadioButtonFor(x => x.IsMale, false) Female
</div>
the provided values (true and false) are the values that the engine will render as the values for the html element i.e.:
<input id="IsMale" type="radio" name="IsMale" value="True">
<input id="IsMale" type="radio" name="IsMale" value="False">
And the checked property is dependent on the Model.IsMale value.
Razor engine seems to internally match the set radio button value to your model value, if a proper from and to string convert exists for it.
So there is no need to add it as an html attribute in the helper method.

To set radio button checked in edit mode in MVC razor view, please trying as follow:
<div class="col-lg-11 col-md-11">
#Html.RadioButtonFor(m => m.Role, "1", Model.Role == 1 ? "checked" : string.Empty)
<span>Admin</span>
#Html.RadioButtonFor(m => m.Role, "0", Model.Role == 0 ? "checked" : string.Empty)
<span>User</span>
#Html.HiddenFor(m => m.Role)
</div>
Hope it help!

Add checked to both of your radio button. And then show/hide your desired one on document ready.
<div class="form-group">
<div class="mt-radio-inline" style="padding-left:15px;">
<label class="mt-radio mt-radio-outline">
Full Edition
<input type="radio" value="#((int)SelectEditionTypeEnum.FullEdition)" asp-for="SelectEditionType" checked>
<span></span>
</label>
<label class="mt-radio mt-radio-outline">
Select Modules
<input type="radio" value="#((int)SelectEditionTypeEnum.CustomEdition)" asp-for="SelectEditionType" checked>
<span></span>
</label>
</div>
</div>

In my case the #checked = "checked" attribute did not work because I was loading default values from the model, which were not equal with the RadioButton value.
Once I changed the loaded values from the model to be equal to the radiobutton value, the button was checked.
For example this will make the radiobutton to be checked by default:
In the model:
response.data = "data"
In the view:
#Html.RadioButtonFor(m => m.data, "data",new {#class="form-check-input"})
<label class="form-check-label">Data (default)</label>

Related

Retrive ids and check related boxes

Using
Laravel 8.54
Livewire 2.6
Laratrust package for roles and permissions
I want to edit the permissions role like that
RolesEdit.php (livewire component)
<?php
namespace App\Http\Livewire\Admin\Roles;
use App\Models\Role;
use Livewire\Component;
use App\Models\Permission;
use Illuminate\Support\Arr;
use Illuminate\Support\Facades\Validator;
class RolesEdit extends Component
{
public $data = [];
public $role;
public $selectedIds = [];
public function mount(Role $role)
{
$this->role = $role;
$this->data = $role->toArray();
}
public function update()
{
$this->data['permissions'] = $this->selectedIds;
$validated = Arr::except($this->validatedData(), ['permissions']);
$this->role->update($validated);
$this->role->permissions()->sync($this->data['permissions']);
}
public function validatedData()
{
return Validator::make($this->data, [
'display_name' => 'required',
'description' => 'required',
"permissions" => "required|array|min:1",
"permissions.*" => "required|distinct|min:1",
])->validate();
}
public function render()
{
$permissions = Permission::all();
return view('livewire.admin.roles.roles-edit', compact('permissions'));
}
}
Roles-edit.blade.php
<div class="mt-1">
<label class="form-label">{{ __('site.display_name') }}</label>
<input wire:model="data.display_name" type="text" class="form-control" placeholder="Enter role name" />
</div>
<div class="mt-1">
<label class="form-label">{{ __('site.role_description') }}</label>
<textarea wire:model="data.description" type="text" class="form-control"
placeholder="Enter Description"></textarea>
</div>
<div class="row w-100">
#foreach ($permissions as $permission)
<div class="col-md-3">
<div class="form-check ms-5">
<input wire:model.defer="selectedIds" class="form-check-input" id="{{ $permission->name }}"
value="{{ $permission->id }}" type="checkbox"
{{ $role->permissions->contains($permission->id) ? 'checked' : '' }} />
<label class="form-check-label" for="{{ $permission->name }}">
{{ $permission->display_name }}</label>
</div>
</div>
#endforeach
</div>
When I open roles-edit view I want to check boxes that have $permission->id related to role so I use
{{ $role->permissions->contains($permission->id) ? 'checked' : '' }}
But it did not work … all checkboxes is unchecked
instead using code:
{{ $role->permissions->contains($permission->id) ? 'checked' : '' }}
try this
#if($role->permissions->contains($permission->id)) checked #endif
also try to add wire:key directive to the parent div of the input element
<div class="form-check ms-5" wire:key="input-checkbox-{{ $permission->id }}">
I suggest you, create an array to retrieve the permissions ids of the role
public $permissionsIds = [];
public function mount(Role $role)
{
$this->role = $role;
$this->data = $role->toArray();
$this->permissionsIds = $this->role->permissions()->pluck('id');
}
// in blade
#if(in_array($permission->id,$permissionsIds)) checked #endif

Submit button is submitting but not saving - MVC

I have tried many things to get the submit button to submit to the database. I'm not getting any errors, and the two error messages for testing, one from the controller, one from the view, are not printing to let me know that it is not working. Upon user hitting submit, it renders and displays the same button- Set Statement, instead of the new text that the user entered. Not sure how to fix or where the problem is.
Here is the code:
Controller:
[HttpPost, ValidateAntiForgeryToken]
public ActionResult Create(TableA Statement)
{
var model = new Test.Models.Tables();
using (var db = new Entities())
if (ModelState.IsValid)
{
TableA tablea = new TableA();
tablea.Statement = model.Statement;
db.TablesA.Add(tablea);
db.SaveChanges();
return RedirectToAction("Index");
}
else
{
return Content("Failed");
}
}
Main View:
<td>
#if (tablea.Statement != null)
{
#Html.DisplayFor(modelItem => tablea.Statement)
<text>|</text>
#Html.ActionLink("Edit", "Edit", new { id = tablea.ID })
}
else
{
Html.RenderAction("PopUp");
var model = new Test.Models.Tables();
if (model.Statement != null) {
<text>Save Successful!</text>
}
}
</td>
Popup View:
#using (Html.BeginForm())
{
#Html.AntiForgeryToken()
<div class="form-horizontal">
=
<hr />
#Html.ValidationSummary(true)
<div class="form-group">
#Html.LabelFor(model => model.Statement, new { #class = "control-label col-md-2" })
<div class="col-md-10">
#Html.EditorFor(model => model.Statement)
#Html.ValidationMessageFor(model => model.Statement)
</div>
</div>
<div class="form-group">
<div class="col-md-offset-2 col-md-10">
<input type="submit" value="Save" onsubmit="Create(Statement)" class="btn btn-default">
</div.. etc>
Popup View is a partial view or what?, I recommend convert it to partial view, and in your controller you can do something like
public ActionResult CreatePartial()
{
var pages = pageRepository.Pages;
return PartialView(pages);
}
and in your view use
#{Html.RenderAction("Popup", "CreatePartial");}
if your model of partial is different of model of main view, if not use:
#Html.RenderPartial("ViewName")

Jquery unobstrusive validation while binding radio button

I have a form which asks user to select Yes or No based on some questions.Intitally none of the option will be selected.If user clicks save button without selecting the option validation should be shown
<div>
<label for="IsSourceCodeCollected" class=" control-label">
Question 1
</label>
</div>
<div>
<label style="width:100px">
#Html.RadioButtonFor(m => m.StudentProjectApprovalTrainer.IsSourceCodeCollected, true, new { #class = "minimal sourceCodeCollected" })
YES
</label>
<label style="width:100px">
#Html.RadioButtonFor(m => m.StudentProjectApprovalTrainer.IsSourceCodeCollected, false, new { #class = "minimal sourceCodeCollected" })
NO
</label>
</div>
#Html.ValidationMessageFor(m => m.StudentProjectApprovalTrainer.IsSourceCodeCollected)
<button type="submit" id="btnSubmit" class="btn btn-info pull-left ">
<i class="fa fa-save"></i>
Save
</button>
Model
[Required(ErrorMessage = "Please select this")]
public bool IsSourceCodeCollected { get; set; }
Javascript
$(document).on("click", "#btnSubmit", function () {
var form = $("#frmAdd");
if (form.valid()) {
alert("hai");
};
return false;
});
When I clicks the save button without selecting Yes or No alert is shown which means form is valid.
How can i solve this scenario ??
Your property is typeof bool which must always have a value (adding the [Required] attribute is not necessary unless you wanted a specific error message). Because its value is either true or false, one of your radio buttons will always be selected when the view is first rendered (and its not possible to 'un-select' both) so the model is always valid.
If you want the option to display both buttons as un-selected and have the validation error display if left un-selected, then you need to change the property to be nullable.
[Required(ErrorMessage = "Please select this")]
public bool? IsSourceCodeCollected { get; set; }

How to pass selected date as input in MVC4?

when i used the below code, i am getting null reference not set to an instance of an object in mvc4. I used FormCollection method to pass date as input. It shows me null value for sd (sd is startdate variable) while i traced out. How to resolve this exception?
Controller:
[HttpPost]
public ActionResult Index(FormCollection formCollection)
{
List<tblGroup> allg = new List<tblGroup>();
using (portalconnectionstring con = new portalconnectionstring())
{
allg = con.grt.OrderBy(m => m.groupname).ToList();
}
ViewBag.disg = new SelectList(allg, "groupid", "groupname");
var sd = formCollection["txtDate"]; //Showing null value here while i traced out
var ed = formCollection["Txtenddate"];
....
.....
}
View:
#using (Html.BeginForm("Index","MyController",FormMethod.Post,new {id="form1"}))
{
<div>
#Html.Label(" ",new { id ="Label1" })
<input id="txtDate" type="text" value="Startdate: "/>
<div>
<input id="Txtenddate" type="text" value="Enddate: "/>
</div>
<div>
#Html.Label("Group Name", new{id="lblGroupName"})
</div>
<div>
#Html.DropDownListFor(model => model.groupid, #ViewBag.disg as SelectList, "select")
#Html.ValidationMessageFor(model=>model.groupid)
</div>
<input type="submit" id="Button1" Value="Submit"/>
</div>
}
You need to give your inputs a name attribute
<input id="txtDate" name="txtDate" type="text" value="Startdate: "/>
However this will be done automatically if you use the html helpers to bind to your model properties, for example #Html.TextBoxFor(m => m.txtDate), in which case you can bind back to you model in the POSt method rather than using FormCollection

Use AngularJS with ASP.NET MVC 4 to detect changes

I have an existing MVC 4 application with several groups of checkboxes and I need to detect when a user has made a change, i.e. checked or unchecked a checkbox. If the user has made a change and they try to navigate away from the page I need to prompt them to save their changes. I am just learning AngularJS, but figured I could use it to detect when a checkbox state has change and also use routes in angular to detect when a user is navigating away from the page.
I have based my code on the answer here. Since the view is already being rendered by MVC I cannot use REST services and angular to populate the model and view.
HTML rendered in the view
<div id="userPermissions" class="userWrapper" ng-app="myApp.User">
<div id="actionCategories" class="section" ng-controller="UserCtrl">
<div class="actionGroupBody">
<div class="actionGroupAction">
<input type="checkbox" value="Create new users"
id="action-f9ae022b-5a53-4824-8a79-f7bbac844b11"
data-action-category="8aefed6e-b76c-453f-94eb-d81d2eb284f9"
ng-checked="isSelected('f9ae022b-5a53-4824-8a79-f7bbac844b11')"
ng-click="updateSelection($event,'f9ae022b-5a53-4824-8a79-f7bbac844b11')"/>Create new users
</div>
<div class="actionGroupAction">
<input type="checkbox" value="Edit users"
id="action-5525d5e7-e1dd-4ec3-9b1d-3be406d0338b"
data-action-category="8aefed6e-b76c-453f-94eb-d81d2eb284f9"
ng-checked="isSelected('5525d5e7-e1dd-4ec3-9b1d-3be406d0338b')"
ng-click="updateSelection($event,'5525d5e7-e1dd-4ec3-9b1d-3be406d0338b')"/>Edit users
</div>
<div class="actionGroupAction">
<input type="checkbox" value="Edit personal account"
id="action-9967c1c2-c781-432b-96df-224da760bfb6"
data-action-category="8aefed6e-b76c-453f-94eb-d81d2eb284f9"
ng-checked="isSelected('9967c1c2-c781-432b-96df-224da760bfb6')"
ng-click="updateSelection($event,'9967c1c2-c781-432b-96df-224da760bfb6')"/>Edit personal account
</div>
</div>
<div class="caption">
<label class="actionGroupCaption">Store</label> <span class="actionCategorySelectAll"><input type="checkbox" value="select all Store" id="7bace6c1-4820-46c2-b463-3dad026991f2" data-action-category="selectall"/>All</span>
</div>
<div class="actionGroupBody">
<div class="actionGroupAction">
<input type="checkbox" value="Access home page"
id="action-fba7e381-4ed8-47ce-8e85-b5133c9ba9f7"
data-action-category="7bace6c1-4820-46c2-b463-3dad026991f2"
ng-checked="isSelected('fba7e381-4ed8-47ce-8e85-b5133c9ba9f7')"
ng-click="updateSelection($event,'fba7e381-4ed8-47ce-8e85-b5133c9ba9f7')"/>Access home page
</div>
<div class="actionGroupAction">
<input type="checkbox" value="Edit settings"
id="action-2d02b77b-14a4-4136-a09f-fd51eecd2dbe"
data-action-category="7bace6c1-4820-46c2-b463-3dad026991f2"
ng-checked="isSelected('2d02b77b-14a4-4136-a09f-fd51eecd2dbe')"
ng-click="updateSelection($event,'2d02b77b-14a4-4136-a09f-fd51eecd2dbe')"/>Edit settings
</div>
<div class="actionGroupAction">
<input type="checkbox" value="Edit products"
id="action-f42f933c-a2b8-42e8-af4b-d52f90f58ddb"
data-action-category="7bace6c1-4820-46c2-b463-3dad026991f2"
ng-checked="isSelected('f42f933c-a2b8-42e8-af4b-d52f90f58ddb')"
ng-click="updateSelection($event,'f42f933c-a2b8-42e8-af4b-d52f90f58ddb')"/>Edit products
</div>
<div class="actionGroupAction">
<input type="checkbox" value="Edit orders"
id="action-92ed258b-c954-46e4-b5c9-a89fdb5c54d9"
data-action-category="7bace6c1-4820-46c2-b463-3dad026991f2"
ng-checked="isSelected('92ed258b-c954-46e4-b5c9-a89fdb5c54d9')"
ng-click="updateSelection($event,'92ed258b-c954-46e4-b5c9-a89fdb5c54d9')"/>Edit orders
</div>
</div>
</div>
</div>
here's the angular code
var app = angular.module('myApp.User', []);
app.controller('UserCtrl', function ($scope) {
$scope.entities = [{ //how to populate with checkboxes state from view? factory maybe similar to below??? // }];
$scope.selected = [];
var updateSelected = function (action, id) {
if (action == 'add' & $scope.selected.indexOf(id) == -1)
$scope.selected.push(id);
if (action == 'remove' && $scope.selected.indexOf(id) != -1)
$scope.selected.splice($scope.selected.indexOf(id), 1);
};
$scope.updateSelection = function ($event, id) {
var checkbox = $event.target;
var action = (checkbox.checked ? 'add' : 'remove');
updateSelected(action, id);
};
$scope.selectAll = function ($event) {
var checkbox = $event.target;
var action = (checkbox.checked ? 'add' : 'remove');
for (var i = 0; i < $scope.entities.length; i++) {
var entity = $scope.entities[i];
updateSelected(action, entity.id);
}
};
$scope.getSelectedClass = function (entity) {
return $scope.isSelected(entity.id) ? 'selected' : '';
};
$scope.isSelected = function (id) {
return $scope.selected.indexOf(id) >= 0;
};
$scope.isSelectedAll = function () {
return $scope.selected.length === $scope.entities.length;
};
});
app.factory('UserDataService', function () {
var service = {}
service.getData = function () {
var actions = $("input[id^=action-]");
return actions;
}
return service;
});
Whenever I click a checkbox none of the $scope functions (.updateSelection, .isSelected, etc.) fire in the controller.