How to make checkbox checked based on the data from database in mvc 4 entity framework? - entity-framework

I am strong checkbox checked data in db. If the checkbox was checked i want to display it as checked in view. Is it possible to achieve this?
Here is my supporting code.
public ActionResult Index()
{
var groups = db.tm_grp_group.Where(a=>a.grp_isactive==true);
var permissions = db.tm_perm_level;
GroupPermissionVM model = new GroupPermissionVM
{
GroupList = new SelectList(groups, "grp_id", "grp_name"),
Permissions = permissions.Select(p => new PermissionVM
{
perm_id = p.perm_id,
perm_levelname = p.perm_levelname
})
};
return View(model);
}
This is index.cshtml
#model Permission.Models.GroupPermissionVM
#{
ViewBag.Title = "Index";
}
<h2>Index</h2>
#using (Html.BeginForm())
{
#Html.LabelFor(m=>m.GroupID)
#Html.DropDownListFor(m => m.GroupID, Model.GroupList, "Please select", new { id = "ddlgrp" })
#Html.EditorFor(m => m.Permissions)
<p><input type="submit" value="Submit" /></p>
}
Inside Home/Editortemplate/PermissionVM.cshtml
#model Permission.Models.PermissionVM
#{
ViewBag.Title = "PermissionVM";
}
<div>
#Html.HiddenFor(m => m.perm_id)
#Html.HiddenFor(m => m.perm_description)
#Html.CheckBoxFor(m => m.perm_status)
#Html.LabelFor(m => m.perm_status,Model.perm_levelname)
</div>
I have table structure like this
grp_id perm_id
1 1 1
2 2 2
permlevel_name perm_status
1 Screen Level True
2 custom Level True
Grp_id is dropdownlistbox in this context. So if i select 1 corresponding permlevel_name is screen level and it is checked. So when i make selection as 1 below screenlevel checkbox should be cheked. Is it possible to achieve this?

in your code where you call PermissionVM.cshtml File.

Related

how multiple row delete using checkbox in yii2

How can I use in GridView delete selected object,in Yii 2 Framework such as following image:
[enter image description here][2]
Try this
<?=Html::beginForm(['controller/bulk'],'post');?>
<?=Html::dropDownList('action','',[''=>'Mark selected as: ','c'=>'Confirmed','nc'=>'No Confirmed'],['class'=>'dropdown',])?>
<?=Html::submitButton('Send', ['class' => 'btn btn-info',]);?>
<?=GridView::widget([
'dataProvider' => $dataProvider,
'columns' => [
['class' => 'yii\grid\CheckboxColumn'],
'id',
],
]); ?>
<?= Html::endForm();?>
This is the controller:
public function actionBulk(){
$action=Yii::$app->request->post('action');
$selection=(array)Yii::$app->request->post('selection');//typecasting
foreach($selection as $id){
$e=Evento::findOne((int)$id);//make a typecasting
//do your stuff
$e->save();
}
}
Or Else
Follow all the steps given in this Link, You will Surely achive your goal.
Yii 2 : how to bulk delete data in kartik grid view?
https://stackoverflow.com/questions/27397588/yii-2-how-to-bulk-delete-data-in-kartik-grid-view/
You can use a column with checkboxes and bulk actions for each row selected.
Here is a related question:
Yii2 How to properly create checkbox column in gridview for bulk actions?
<?php
$url = Url::to(['user/delete']);
$this->registerJs('
$(document).on("click", "#delete_btn",function(event){
event.preventDefault();
var grid = $(this).data(\'grid\');
var Ids = $(\'#\'+grid).yiiGridView(\'getSelectedRows\');
var status = $(this).data(\'status\');
if(Ids.length > 0){
if(confirm("Are You Sure To Delete Selected Record !")){
$.ajax({
type: \'POST\',
url : \''.$url.'\' ,
data : {ids: Ids},
dataType : \'JSON\',
success : function($resp) {
if($resp.success){
alert(resp.msg);
}
}
});
}
}else{
alert(\'Please Select Record \');
}
});
', \yii\web\View::POS_READY);
?>
[1]: http://i.stack.imgur.com/iFjT1.png
I have succeeded in deleting multiple rows in gridview Yii2 by doing the following:
Create button in index.php
<p>
<button type="button" onclick="getRows()" class="btn btn-success">Delete Bulk</button>
</p>
Add javascript code in index.php to perform the event of getting the checked rows from the GridView widget.
<script>
function getRows()
{
//var user_id as row_id from the gridview column
// var list = [] is an array for storing the values selected from the //gridview
// so as to post to the controller.
var user_id;
var list = [];
//input[name="selection[]"] this can be seen by inspecting the checkbox from your //gridview
$('input[name="selection[]"]:checked').each(function(){
user_id = this.value;
list.push(user_id);
});
$.ajax({
type: 'post',
url:'index.php?r=student-detail-update/bulk',
data: {selection: list},
});
}
</script>
Put this code in your contoller
if ($selection=(array)Yii::$app->request->post('selection')) {
foreach($selection as $id){
$StudentDetailUpdates = StudentDetailUpdate::find()
->where(['user_id' => $id])
->all(); //....put your staff here
}

Keep select value on change with laravel

I am having a paginated backend table with db-data. The admin person can filter that table for data status. This happens via ajax. Everything works fine but I do not get the selected filter value to remain selected when I click on the second pagination link.
E.g. I choose select option: '1' => 'Active' so that only db-rows show up that have a status of 1. But when I then click on the second pagination link to see the next 20 rows then again it also displays the inactive db-rows. How would I get the selected option to remain selected in this situation? I tried Input::old('status') and passing $selected to view as below but no success. Thank you for any hint!
View:
<form id="filter_form" onsubmit="" action="<?php echo URL::action('countries#anyIndex'); ?>">
<?php echo Form::select('filter_status', funcs::get_status_options(), $selected, array('id' => 'filter_status')); ?>
</form>
Ajax:
$(function(){
$("#filter_status").on('change', function(){
frm = $("#filter_form");
frm.serialize();
status = $('#filter_status').val();
$.ajax({
type: "POST",
url: $(frm).attr('action'),
data: {status: status},
success: function(data){
$("#list").html(data.list);
},
dataType: "json"
});
});
});
Controller:
class countries extends BaseController {
public $filter = array(0,1,2);
function anyIndex()
{
$data['title'] = "Countries list";
if(Input::has('status')){
$status = Input::get('status');
if($status != 2){
$this->filter = array($status);
}
}
$d['items'] = $this->_getItems(20);
if(Request::ajax()){
$data['list'] = View::make('admin/countries/countries_list', $d)->withInput($status)->render();
return Response::json($data);
}
$data['selected'] = $this->filter;
$data['list'] = View::make('admin/countries/countries_list', $d);
return View::make('admin/admin_layout')->nest('view', 'admin/countries/countries_view', $data);
}
private function _getItems($paginate)
{
$items = Country::whereIn('status', $this->filter)->paginate($paginate);
return $items;
}
}

Telerik MVC Grid not sorting when reloaded

My Telerik MVC grid is Ajax bound and I need to ability to apply custom filtering via two checkboxes (in the DIV at the top). When a checkbox is checked, the parameters would be set and the grid is reloaded. This is working fine. During the initial load the data is sorted based on the sorting settings in Telerik, but after I click a checkbox, the data is ordered by record Id and no longer by Priority. If I then hit F5 the page is reloaded and the data is sorted correct. The sorting might be a parameter for grid.rebind() or provided in OnDataBinding, but so far I have not found what I am looking for.
QUESTION: How do I specify the sorting order in the OnDataBinding or perhaps in another client event.
Here is my code:
<div style="float:right;width:600px;text-align:right">
<span>My Items <%=Html.CheckBox("newItems") %></span>
<span>Closed Items <%=Html.CheckBox("Inactive") %></span>
</div>
<% Html.Telerik().Grid<IssueModel>()
.Name("Grid")
.PrefixUrlParameters(false)
.Columns(col =>
{
col.Bound(o => o.Title);
col.Bound(o => o.Priority).Width(50).Title("Priority ID");
col.Bound(o => o.PriorityName).Width(100).Title("Priority");
col.Bound(o => o.IssueStateName).Width(100).Title("Status");
col.Bound(o => o.AssignedToName).Width(140).Title("Assigned To");
})
.DataBinding(d => d.Ajax().Select("AjaxSelect", "Ticket", new { isNew = false, isInactive = false }))
.ClientEvents(e => e.OnDataBinding("onDataBinding"))
.Sortable(s => s
.SortMode(GridSortMode.MultipleColumn)
.OrderBy(order =>
{
order.Add(o => o.Priority);
order.Add(o => o.Sequence);
})
)
.Pageable(p => p.PageSize(15))
.Filterable()
.Render();
%>
<script type="text/javascript">
function onDataBinding(e) {
e.data = {
isNew: $("#newItems").is(':checked'),
isInactive: $("#Inactive").is(':checked')
};
e.orderBy = "Severity~desc~Ranking~asc";
}
$("input[type='checkbox']").click(function () {
var grid = $('#Grid').data('tGrid');
var param = {
isNew: $("#newItems").is(':checked'),
isInactive: $("#Inactive").is(':checked')
};
grid.rebind(param);
});
</script>
I found the solution in case others need the answer. I used grid.sort() in place of grid.rebind(); The sort method takes a string in the format: column-name dash direction. Example First
<script type="text/javascript">
function onDataBinding(e) {
e.data = {
isNew: $("#newItems").is(':checked'),
isInactive: $("#Inactive").is(':checked')
};
}
$("input[type='checkbox']").click(function () {
var grid = $('#Grid').data('tGrid');
var param = {
isNew: $("#newItems").is(':checked'),
isInactive: $("#Inactive").is(':checked')
};
grid.sort("Severity-desc~Ranking-asc";);
//grid.rebind(param);
});
</script>

Asp.net MVC 2 CascadingDropDown

Hi, this is my Controller Code:
public ActionResult Create()
{
makelist = new SelectList(db.CountryMasters.ToList(), "CountryID", "CountryName",1);
ViewData["CounrtyMaster"] = makelist;
var modelList = new CascadingSelectList(clientMasterManagement.GetState(makelist.SelectedValue.ToString()), "StateID", "StateName");
ViewData["StateMaster"] = modelList;
return View("Create");
}
and this is my View Code:
<div class="editor-field">
<%= Html.DropDownList("CountryID", ViewData["CounrtyMaster"] as SelectList)%>
<%= Html.ValidationMessageFor(model => model.CountryID) %>
</div>
<%= Html.CascadingDropDownList("StateMaster","CountryMaster")%>
when I select upper list it's not affecting the second one, can anyone help me here???
User CascadingSelectList function instead of SelectList in your controller action
var makelist = new SelectList(db.CountryMasters.ToList(), "CountryID", "CountryName",1); ViewData["CounrtyMaster"] = makelist;
var modelList = new CascadingSelectList(clientMasterManagement.GetState(makelist.SelectedValue.ToString()), "StateID", "StateName");
ViewData["StateMaster"] = modelList;
Html.CascadingDropDownList is not a standard MVC helper. I take it that you are using Stephen Walther's helper. If so this question will help you out:
ASP.NET MVC - Cascading Drop Down

How to preselect item in Html.DropDownlListFor()

How can i preselect item in Html.DromDownListFor() ?
i have code in view which inserts items to DropDownListFor
<div class="editor-field">
<%var mesta = new List<SelectListItem>();
SelectListItem aa = new SelectListItem();
aa.Text = "---------VYBER MESTO---------";
aa.Value = "0";
mesta.Add(aa);
foreach (var item in Model.MestoTbl)
{
SelectListItem a = new SelectListItem();
a.Text = item.Mesto;
a.Value = item.MestoId.ToString();
mesta.Add(a);}%>
<%: Html.DropDownListFor(model => model.Mesto.MestoId, mesta)%>
<%: Html.ValidationMessageFor(model => model.Mesto.MestoId)%>
</div>
this inserts 2 values MestoId & Mesto ....when i click on some database record (edit field)
example =>
Name Surname Mesto
--------------------
Peter Malik Snina
Snina => Mestoid = 2
I wanna get ....
if i click to edit record of Peter Malik the Html.DropDownListFor automatically preselect item Snina in list.
You could use the SelectList constructor. See here.
thanks now it is working.
<%: Html.DropDownListFor(model => model.Mesto.MestoId, new SelectList(mesta, "Value", "Text", Model.Ziak.MestoId))%>