How to work with two columns containing different GetSelectLink method in the same WebGrid? - webgrid

I am a beginner in ASP.Net MVC3 and trying implement a table using WebGrid I faced off with a problem.
In an row of this table I have "Id" and "Name" (came from DB) and two links more: "Edit" and "Delete". These links are executed using item.GetSelectLink() inside the same web grid, as follows:
<div id="grid">
#{
var grid = new WebGrid(source: Model, rowsPerPage: 30, canPage: true, canSort: true, fieldNamePrefix: "gridDivisoes_", selectionFieldName: "Id");
}
#grid.GetHtml(
tableStyle: "table", headerStyle: "header", footerStyle: "footer", alternatingRowStyle: "alternate",
columns: grid.Columns(
grid.Column("Name", header: "Division", style: "text-align-left", canSort: true),
grid.Column(header: "Update?", style: "text-align-center", format: (item) => item.GetSelectLink("[update]")),
grid.Column(header: "Delete?", style: "text-align-center", format:(item) => item.GetSelectLink("[delete]"))
))
if(grid.HasSelection)
{
if("[delete]" == grid. ????) //click's origin: "[delete]"
{
<input type="hidden" value="#Html.AttributeEncode(Model.ElementAt(grid.SelectedIndex).Id)" id="Id" name="Id" />
<input type="hidden" value="#Html.AttributeEncode(Model.ElementAt(grid.SelectedIndex).Name)" id="Name" name="Name" />
<br />
<br />
<br />
<p>Do you really want to delete the division "#Model.ElementAt(grid.SelectedIndex).Name" ?</p>
<p><input type="submit" value="Delete" /></p>
}
if ("[update]" == grid. ????) //click's origin: "[update]"
{
<input type="hidden" value="#Html.AttributeEncode(Model.ElementAt(grid.SelectedIndex).Id)" id="Id" name="Id" />
<div class="editor-label">
Name
</div>
<div class="editor-field">
#Html.TextBoxFor(Page => Page.ElementAt(grid.SelectedIndex).Name)
#Html.ValidationMessageFor(Page => Page.ElementAt(grid.SelectedIndex).Name)
</div>
<br />
<br />
<p><input type="submit" value="Update"/></p>
}
}
</div>
How could I get the click's origin and execute the grid.HasSelection accordingly "Delete" or "Update" options?
I can't believe that there I can't choose one between these options, select a row and, at same time, just to know the click origin.
How could I do a comparison? Something like that if("[delete]" == grid. ????) ?

Amanda, if i understood you correctly, you want to be able to both edit and delete a row, right?
If so, you can try this:
columns: grid.Columns(
grid.Column("Name", header: "Division", style: "text-align-left", canSort: true),
grid.Column(format: (item) => Html.ActionLink("Update?", "Update", new { updateId = item.ID })),
grid.Column(format: (item) => Html.ActionLink("Delete?", "Update", new { deleteId = item.ID }))
))
You can even use Ajax to render a partial with your row values, if you like

Related

Filtering items, checkbox issue laravel + vue js

I have a "Messages" table in the database. I am trying to make a filter by read/unread
For the filter, I am trying to make two checkboxes, and a "isread" variable, however I cant manage to make it work, heres what I have:
<input
type="checkbox"
id="1"
class="read"
v-model="isread"
:value="1"
/>
<input
type="checkbox"
id="0"
class="unread"
v-model="isread"
:value="0"
/>
The issue is that I get tons of errors in the console, plus the checkboxes get ticked/unticked at the same time (like its the same checkbox). My expected result, is that the variable "isread" stores value "0" if the "0" checkbox is checked, and "1" if the "1" is checked. Or, if both - both values get stored. Could you help me?
If I understand your requirement correctly, You are trying to filtered out the existing list of messages based on the read and unread messages. If Yes, You can try this solution :
var vm = new Vue({
el:"#app",
data:{
messages: [
'read1',
'read2',
'read3',
'read4',
'unread5',
'unread6',
'unread7',
'unread8',
'read9',
'read10',
],
isread: null,
isunread: null,
filteredMessages: []
},
mounted() {
this.filteredMessages = this.messages;
},
methods: {
check(e) {
if (e.target.checked && (e.target.value === '1')) {
this.filteredMessages = this.messages.filter((item) => item.indexOf('unread') === -1)
this.isunread = 0;
} else if (e.target.checked && (e.target.value === '0')) {
this.filteredMessages = this.messages.filter((item) => item.indexOf('unread') !== -1)
this.isread = 0;
}
}
}
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.17/vue.js"></script>
<div id="app">
Read :<input
type="checkbox"
id="1"
class="read"
v-model="isread"
:value="1"
#change="check($event)"
/>
Unread :<input
type="checkbox"
id="0"
class="unread"
v-model="isunread"
:value="0"
#change="check($event)"
/>
<ul class="list">
<li v-for="(message, index) in filteredMessages" :key="index">{{ message }}</li>
</ul>
</div>

Is it possible to capture the key associated with a datalist item upon selecting an item from the list?

I have the below code to populate a search box with datalist items. The key of the datalist items is set to u.userID and the display is set to u.name. When an item is selected, I can get the u.name which is displayed. How can I get the underlying key associated with the item?
<div class="form-group">
<div class="input-group mb-3">
<input type="search" id="usersearch" list="userList" class="form-control" placeholder="Search user"
#keydown.enter="addUser(selectedUser)" v-model="selectedUser" v-on:input="changingUser($event)" />
<div class="input-group-append">
<span class="input-group-text" id="basic-addon2"> <b-icon icon="search"></b-icon></span>
</div>
</div>
<datalist id="userList">
<option v-for="u in users" :key="u.userID">{{ u.name }}</option>
</datalist>
</div>
methods: {
addUser(user) {
console.log(user);
},
changingUser(e) {
if (!e.inputType) {
this.addUser(this.selectedUser);
}
}
}
It's not possible to get the key from the selected datalist.option because the input-event does not link to the <option> in any way.
While not ideal, you could lookup the user by name, and access the userID:
export default {
methods: {
addUser(username) {
const user = this.users.find(u => u.name === username)
console.log('addUser ID', { userID: user?.userID })
},
}
}
demo

Bootbox with Aurelia

I know that I can directly add HTML forms via the message, however can I do something like:
message: document.getElementById('formContent').innerHTML?
Is this my DIV.
<div class="col-sm-6">
<div class="row">
<div class="col-sm-6">
<div class="form-group">
<label class="control-label">Search For Options</label>
<input disabled.bind="readonly" type="text" class="form-control" value.bind="SearchForOptions">
</div>
</div>
<div class="col-sm-6">
<div class="form-group">
<label class="control-label">AND / OR</label>
<dropdown disabled.bind="readonly" options.bind="core.GetOptionsList()" value.bind="OptionId" selected.bind="OptionId" />
</div>
</div>
</div>
<div class="row">
<div class="col-sm-12">
<button click.trigger="cancelSearch()" class="btn btn-default" type="button">Cancel</button>
<button click.trigger="searchOptions()" class="btn btn-info" type="button" disabled.bind="!canSearch">Search</button>
</div>
</div>
</div>
core. GetOptionsList() - Aureila
import {Core} from 'admin/core';
#inject(Core)
constructor(core){
this.core = core;
}
UPDATE
Its pulling the content of the <div> however not the values from the DD
bootbox.dialog({
title: "This is a form in a modal.",
message: jQuery('#search').html(),
buttons: {
success: {
label: "Save",
className: "btn-success",
callback: function () {
//var name = $('#name').val();
//var answer = $("input[name='awesomeness']:checked").val()
//Example.show("Hello " + name + ". You've chosen <b>" + answer + "</b>");
}
}
}
});
UPDATE
addNew(){
bootbox.dialog({
title: "Search Options",
message: jQuery('#searchCriteria').html(),
buttons: {
cancel: {
label: 'Cancel',
className: 'btn btn-default'
},
confirm: {
label: 'Search',
className: 'btn-primary btn btn-info',
callback: function() {
var text = $("#SearchForOptions").val();
var dropdown = $("#OptionId").val();
alert(text);
alert(dropdown);
if (!text || !dropdown){
return false;
} else {
this.searchOptions(text, dropdown);
}
}
},
}
});
}
Sorry, I forgot to put this in my original question. dropdown is a custom element, which takes the following:
options: list of options
value: value of selected option
selected: value of selected option
My main issue is can I use aureila i.e. binding elements such as value.bind, or do I need to build my DD manually etc? As it currently looks like I cannot use any binding.

how to set radio button checked in edit mode in MVC razor view

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>

DataTables warning: Requested unknown parameter '4' from the data source for row ''

Are Days and days that I'm looking for this problem, but nothing resolved it!
This warning appear after the add of a Student to my Database. The persist of the Data is Ok, so i need to hide this error or adjust it.
So i have a Datables that give me this error:
This is my html code:
<script type="text/javascript">
$(document).ready(function () {
$("#companies").dataTable({
"bServerSide": true,
"sAjaxSource": "/studentiSource",
"bProcessing": true,
"sPaginationType": "full_numbers",
"bJQueryUI": true,
"aoColumns": [
{ "sName": "ID", "mDataProp": null,
"bSearchable": false,
"bSortable": false,
"bVisible": false
},
{ "sName": "NOME",},
{ "sName": "COGNOME"},
{ "sName": "USERNAME"},
{ "sName": "PASSWORD" },
{ "fnRender": function (oObj) {
console.log(oObj);
return '<a href=${pageContext.request.contextPath}/modificaStudente.jsp?id=' + oObj.aData[0] + '>' + 'Gestisci' + '</a>';
}}
]
}).makeEditable({
sUpdateURL : "/updateStudenti" ,
sAddURL: "/studenteServlet",
sDeleteURL: "/deleteStudenti",
fnShowError: function (message, action) {
switch (action) {
case "update":
jAlert(message, "Update failed");
break;
case "delete":
jAlert(message, "Delete failed");
break;
case "add":
$("#lblAddError").html(message);
$("#lblAddError").show();
break;
}
},
fnStartProcessingMode: function () {
$("#processing_message").dialog();
},
fnEndProcessingMode: function () {
$("#processing_message").dialog("close");
}
});
});
And the table is:
<div id="container">
<div id="demo_jui">
<button id="btnAddNewRow" value="Ok">Aggiungi nuovo studente...</button>
<button id="btnDeleteRow" value="cancel">Rimuovi utente selezionato</button>
<div id="processing_message" style="display:none" title="Processing">Attendere.. Caricamento dati in corso</div>
<table id="companies" class="display">
<thead>
<tr>
<th>ID</th>
<th>Nome</th>
<th>Cognome</th>
<th>Username</th>
<th>Password</th>
<th>Dispense</th>
</tr>
</thead>
<tbody >
</tbody>
</table>
</div>
<form id="formAddNewRow" action="#" title="Aggiungi nuovo studente">
<label id="lblAddError" style="display:none" class="error"></label>
<input type="hidden" id="id" name="id" value="-1" rel="0" />
<input type="hidden" value="aggiungi" name="action">
<label for="name">Nome</label><input type="text" name="nome" id="name" class="required" rel="1" />
<br />
<label for="name">Cognome</label><input type="text" name="cognome" id="address" rel="2" />
<br />
<label for="name">Username</label><input type="text" name="username" id="postcode"/>
<br />
<label for="name">Password</label><input type="text" name="password" id="town" rel="3"/>
<br />
</form>
</div>
I'm using Datatables 1.9.4
I cant give you a definitive answer, since you did not include the JSON response from the server.
This message usally means that DataTables is looking at your data source for array position 4 (which is the fifth element -- the password field) and not finding it.
You should make sure that you are returning a response with all the fields specified in the datatables definition, including the password field.
The sixth element of your JSON array doesn't contain the value for key '4' because you're fetching a null value, try to parse your JSON array to http://jsoneditoronline.org/ and you'll see it.