Format webgrid column bound to collection? - webgrid

Here is my webgrid:
<div id="grid">
#grid.GetHtml(
tableStyle: "grid",
headerStyle: "head",
alternatingRowStyle: "alt",
columns: grid.Columns(
grid.Column("FullName", "Name"),
grid.Column("User.Email", "Email", format:##item.User.Email),
grid.Column("User.PhoneExtension", "Extension"),
grid.Column("ManagerName", "Manager"),
grid.Column("User.Roles", "Roles"),
grid.Column("", format: (item) => new HtmlString(Html.ActionLink("Edit", "Edit", new { userName = item.User.UserName } ).ToString() + "|" + Html.ActionLink("Details", "Details", new { userName = item.User.UserName }).ToString()))
)
)
User.Roles is a collection of string. How can I use "format: " to output each role, then a linebreak in that cell? Thanks in advance.

You can user html helpers to accomplish that:
...
grid.Column(columnName: "User.Roles", header: "Roles", format: #<text>#Html.RenderUserRoles((List<String>)item.User.Roles)</text>)
...
The helper would be something like...
...
public static string RenderUserRoles(this HtmlHelper helper, List<string> roles)
{
string result = string.Empty;
foreach (var item in roles)
{
result += item + " - ";
}
result += "<br>";
return result;
}
...
Not tested, but should be a guide to get to your own solution, since you can change the helper to render things the way you want.

Related

Update Cascading Dropdown in Mvc5

Hi i want to know how to update or edit cascading dropdown like (Country,state,City)in mvc5.I have created 3 cascading dropdowns Country State city.If i select Country State will append in state dropdownn like wise city. Now i save these 3 dropdown values in table successfully. But now i stuck with edit option. I donno how to bind the saved value to these dropdowns in edit from.
My model
public class UCustomerManagementViewModel
{
public string UCountry { get; set; }
public string UState { get; set; }
public string UCity { get; set; }
}
My Controller code
public JsonResult GetCountries()
{
var Countries = db.Countries.ToList();
return Json(Countries, JsonRequestBehavior.AllowGet);
}
public JsonResult GetStatesByCountryID(string countryId)
{
int id = Convert.ToInt32(countryId);
var states = db.States.Where(d => d.CountryID == id).Select(e => new { e.UID, e.StateName }).ToList();
return Json(states, JsonRequestBehavior.AllowGet);
}
public JsonResult GetCityByStateID(string stateId)
{
int id = Convert.ToInt32(stateId);
var Cities = db.Cities.Where(d => d.StateID == id).Select(e => new { e.UID, e.CityName }).ToList();
return Json(Cities, JsonRequestBehavior.AllowGet);
}
public ActionResult Update(int id)
{
CustomerManagement cc = db.CustomerManagements.Find(id);
ViewBag.CountryID = new SelectList(db.Countries.Where(d => d.CountryID.ToString() == cc.Country.ToString()), "CountryID", "CountryName",cc.CountryID);
var ucusmanvm = new UCustomerManagementViewModel();
ucusmanvm.UCountry = cc.Country;(here i get value 1)
ucusmanvm.UState = cc.State;(here i get value 2)
ucusmanvm.UCity = cc.City;(here iget value 2)
return View(ucusmanvm);
}
here i pass all the value to view form
My View Code
$(document).ready(function () {
debugger;
$.ajax({
type: "GET",
url: '#Url.Action("GetCountries", "FrmCustomerManagement")',
datatype: "Json",
success: function (data) {
$.each(data, function (index, value) {
$('#dropdownCountry').append('<option value="' + value.CountryID + '">' + value.CountryName + '</option>');
});
}
});
$('#dropdownCountry').change(function () {
debugger;
$('#dropdownState').empty();
var cval = $('#dropdownCountry').val()
$.ajax({
type: "POST",
url: '#Url.Action("GetStatesByCountryID", "FrmCustomerManagement")',
datatype: "Json",
data: { countryId: cval },
success: function (data) {
$.each(data, function (index, value) {
$('#dropdownState').append('<option value="' + value.UID + '">' + value.StateName + '</option>');
});
}
})
});
$('#dropdownState').change(function () {
debugger;
$('#dropdownCity').empty();
var sval = $('#dropdownState').val()
$.ajax({
type: "POST",
url: '#Url.Action("GetCityByStateID", "FrmCustomerManagement")',
datatype: "Json",
data: { stateId: sval },
success: function (data) {
$.each(data, function (index, value) {
$('#dropdownCity').append('<option value="' + value.UID + '">' + value.CityName + '</option>');
});
}
})
});
#Html.DropDownList("dropdownCountry", new SelectList(string.Empty, "Value", "Text"), "Please select a country", new { #class = "form-control", #width = "80%", #value=Model.UCountry})
<div class="col-sm-8">
<label>State</label>
#Html.DropDownList("dropdownState", new SelectList(string.Empty, "Value", "Text"), "Please select a State", new { #class = "form-control", #width = "80%" , #value=Model.UState})
</div>
<div class="col-sm-8">
<label>City</label>
#Html.DropDownList("dropdownCity", new SelectList(string.Empty, "Value", "Text"), "Please select a City", new { #class = "form-control", #width = "80%" , #value=Model.Ucity})
</div>
Here in update from also i acheive Cascading dropdown using ajax. but in update form i donno how to bring the save value to drop downs(Country city, state) from controller to view (eg i saved UAE in Country Dropdown but in edit mode i donno how to bring UAE value in Country dropdown ).I passed value from controller but i donno how to bind that value in view.please any one help me to resolve this issue .

MVC4 Ajax.BeginForm routeValues converted to Type Name in HTML

I'm using Ajax.BeginForm in a MVC 4 Razor View.
#model EditViewDefinition
#{
RouteValueDictionary postParams = new RouteValueDictionary();
postParams.Add("entityUid", Model.EntityUid);
postParams.Add("entityId", ViewBag.entityId);
postParams.Add("viewUid", Model.UID);
string viewContainerId = "viewcontent_" + Model.UID.ToString().ToLower() + "_" + ViewBag.entityId.ToString();
}
then
using (Ajax.BeginForm("Edit", postParams, new AjaxOptions() { HttpMethod = "Post", OnSuccess = "submitSuccess('" + viewContainerId + "')" }))
{
...
}
Now when I check the resulting HTML in the browser, I get:
<form id="form0"
action="/View/Edit?Count=3&Keys=System.Collections.Generic.Dictionary%602%2BKeyCollection%5BSystem.String%2CSystem.Object%5D&Values=System.Collections.Generic.Dictionary%602%2BValueCollection%5BSystem.String%2CSystem.Object%5D"
method="post"
data-ajax-success="submitSuccess('viewcontent_fb1a8d4c-fd30-4da4-b11c-bff99f3bb74f_1')"
data-ajax-method="Post"
data-ajax="true">
...
</form>
Why am I getting System.Collections.Generic.Dictionary%602%2BKeyCollection%5BSystem.String%2CSystem.Object in the action attribute instead of action="/View/Edit?entityUid=uid&entityId=1&viewUid=uid?
Thanks to Stephen Muecke's comment. I used var postParams = new { entityUid = Model.EntityUid, entityId = ViewBag.entityId, viewUid = Model.UID }; which worked.
Many Thanks Stephen.

How to pass 2 parameters through $.getJson in MVC?

I am doing my application in MVC. I did cascading dropdownlist in list . While selecting the value from dropdown i passed the value by $.getJson() to the controller. I am passing one id to the controller. My problem is i need to pass 2 id's to the controller. Is it possible to send 2 ids to the controller?
My View page is
<div>
#Html.DropDownList("Business", ViewBag.CategoryID as SelectList ,"Select the Business Category", new { id = "Business" })
</div>
<div>
<label>Select the Service Type</label>
#*<select id="Buname" name="buname" style="width:150px"></select>*#
#Html.DropDownList("Service", ViewBag.Service as SelectList,"Select", new { id = "Service", name ="buname"})
</div>
<div>
<label> Select the Location</label>
<select id="Location" name="location" style="width:150px"></select>
</div>
<div>
<label> Select the Location</label>
<select id="Employee" name="employee" style="width:150px"></select>
</div>
<script type="text/javascript">
$(function () {
$('#Business').change(function () {
$.getJSON('/Appt/Categories/' + $('#Business').val(), function (data) {
var items = '<option> Any Hospital</option>'
$.each(data, function (i, Service) {
debugger;
items += "<option value='" + Service.Value + "'>" + Service.Text +
"</option>";
});
$("#Service").html(items);
});
});
$('#Service').change(function () {
$.getJSON('/Appt/Location/' + $('#Service').val(), function (data) {
var items = '<option> Any Location </option>';
$.each(data, function (i, location) {
items += "<option value='" + location.Value + "'>" + location.Text +
"</option>";
});
$("#Location").html(items);
});
});
$('#Location').change(function () {
$.getJSON('/Appt/Employee/' + $('#Location').val(), function (data) {
var items = '<option> Any Employee </option>';
$.each(data, function (i, employee) {
items += "<option value='" + employee.Value + "'>" + employee.Text +
"</option>";
});
$("#Employee").html(items);
$("Service").html(items);
});
});
});
</script>
My Controller code is
public ActionResult WaitingList()
{
SYTEntities ca = new SYTEntities();
ViewBag.CategoryId = new SelectList(ca.BusinessCategories.ToList(), "CategoryId", "CategoryName");
ViewBag.Service = new SelectList(ca.tblBusinessCategories.ToList(), "BusinessID", "BusinessName");
return View();
}
public JsonResult Categories(int id)
{
SYTEntities db = new SYTEntities();
var business = from s in db.tblBusinessCategories
where s.CategoryId == id
select s;
return Json(new SelectList(business.ToArray(),"BusinessID", "BusinessName"), JsonRequestBehavior.AllowGet);
}
public JsonResult Location(int id)
{
SYTEntities db = new SYTEntities();
var location = from s in db.tblBusinessLocations
where s.BusinessID == id
join loc in db.tblLocations
on s.LocID equals loc.LocationId
select loc;
return Json(new SelectList(location.ToArray(), "LocationId", "LocationName"), JsonRequestBehavior.AllowGet);
}
public JsonResult Employee(int id)
{
SYTEntities db = new SYTEntities();
var emp = from s in db.Employees
where s.LocationId == id && s.BusinessID == 91
select s;
return Json(new SelectList(emp.ToArray(), "EmpId", "EmpName"), JsonRequestBehavior.AllowGet);
}
In public JsonResult Employee(int id) i need to pass ('#Service') value.
Is it possible to do? Can anyone please help me?
You can pass as many values as you want using the data parameter of jQuery.getJSON
var url = '#Url.Action("Categories", "Appt")'; // don't hard code your urls!
$.getJSON(url, { id: $('#Business').val(), otherProperty: anotherValue }, function (data) {
Yes you just need to add one more parameter to the Controller Action as below.
public JsonResult Categories(int id, int id2)
{
SYTEntities db = new SYTEntities();
var business = from s in db.tblBusinessCategories
where s.CategoryId == id
select s;
return Json(new SelectList(business.ToArray(),"BusinessID", "BusinessName"), JsonRequestBehavior.AllowGet);
}
and the below change in you View
$.getJSON('/Appt/Categories/' + $('#Business').val(), { id2: ('#otherId2').val() }, function (data) {
var items = '<option> Any Hospital</option>'
$.each(data, function (i, Service) {
debugger;
items += "<option value='" + Service.Value + "'>" + Service.Text +
"</option>";
});
$("#Service").html(items);
});

Using system.linq.lookup values for dropdownfor mvc 4

In MVC 4 I am using razor to get items from collection and assign it to a var. The var is of type
{System.Linq.Lookup<<>f__AnonymousType0<string,System.Guid,string>,IMEModels.InterviewManagement.Interviewer>.Grouping}
This is my code
var ChairList = Model.Interviewers.Where(d => d.LocKey == Convert.ToString(location.LocationKey) && d.IsChair && d.Date == date.Date).GroupBy(x => new { x.FullDetails, x.InterviewerId, x.Preference }).ToList();
And how it looks in watch:
- ChairList Count = 1 System.Collections.Generic.List<System.Linq.IGrouping<<>f__AnonymousType0<string,System.Guid,string>,IMEModels.InterviewManagement.Interviewer>>
- [0] {System.Linq.Lookup<<>f__AnonymousType0<string,System.Guid,string>,IMEModels.InterviewManagement.Interviewer>.Grouping} System.Linq.IGrouping<<>f__AnonymousType0<string,System.Guid,string>,IMEModels.InterviewManagement.Interviewer> {System.Linq.Lookup<<>f__AnonymousType0<string,System.Guid,string>,IMEModels.InterviewManagement.Interviewer>.Grouping}
+ [System.Linq.Lookup<<>f__AnonymousType0<string,System.Guid,string>,IMEModels.InterviewManagement.Interviewer>.Grouping] {System.Linq.Lookup<<>f__AnonymousType0<string,System.Guid,string>,IMEModels.InterviewManagement.Interviewer>.Grouping} System.Linq.Lookup<<>f__AnonymousType0<string,System.Guid,string>,IMEModels.InterviewManagement.Interviewer>.Grouping
- Key { FullDetails = "TEST - Richard Jackson - (80020937)", InterviewerId = {ff1efad7-7176-4fab-a1bb-30f6656c8880}, Preference = "Available" } <Anonymous Type>
FullDetails "TEST - Richard Jackson - (80020937)" string
+ InterviewerId {ff1efad7-7176-4fab-a1bb-30f6656c8880} System.Guid
Preference "Available" string
+ Raw View
I want to use this for a dropdownfor but it doesn't recognise the key and value that I am giving for it:
#Html.DropDownListFor(m => m.InterviewSchedules[location.InterviewDates.IndexOf(date)].ChairId, new SelectList(ChairList, "InterviewerId", "FullDetails"))
Can someone help me with this piece of code? It's possible that there is an easier way of doing this that I am unaware of.
For view
#Html.DropDownListFor(m => m.InterviewSchedules[location.InterviewDates.IndexOf(date)].ChairId,, ViewData["ReturnList"] as SelectList, new { #class = "form-control" })
For Code (Return as viewData)
public SelectList ReturnList(Guid UID) {
var ChairList = Model.Interviewers.Where(d => d.LocKey == Convert.ToString(location.LocationKey) && d.IsChair && d.Date == date.Date).GroupBy(x => new { x.FullDetails, x.InterviewerId, x.Preference }).ToList();
List<SelectListItem> selectItems = ChairList.Select(s => new SelectListItem() {
Text =FullDetails,
Value = InterviewerId.ToString(),
Selected = false
}
).ToList();
selectItems.Insert(0, new SelectListItem() {
Text = " --Select -- ",
Value = null,
Selected = false
});
SelectList selectList = new SelectList(selectItems, "Value", "Text");
return selectList;
}

how to Filter webgrid in mvc4 based on textbox input and dropdownList input

I am still in learning curve of mvc4 . I know how to bind a webgrid in mvc4 . But my doubt is can anyone share me the idea how to bind webgrid based on filter conditions from textbox input and dropdownList input. For eg : If textbox has a date "11/15/2013" and dropdownList has the doctor name "Charles" then i need to show in gridview the list of patients who has appointment with doctor " charles " on "11/15/2013" .
code
<div id="gridContent">
#grid.GetHtml(
fillEmptyRows: true,
tableStyle: "webGrid",
alternatingRowStyle: "alternate-row",
headerStyle: "grid-header",
footerStyle: "grid-footer",
mode: WebGridPagerModes.All,
firstText: "<< First",
previousText: "< Prev",
nextText: "Next >",
lastText: "Last >>",
columns: new[] {
grid.Column("PatientID"),
grid.Column("PatientName"),
grid.Column("Age"),
grid.Column("DOB"),
grid.Column("Sex"),
grid.Column("Phone"),
grid.Column("Mobile"),
grid.Column("City"),
grid.Column("PinCode"),
// grid.Column("Dr_Remarks",header:"Remarks",style:"left"),
//grid.Column("Dr_Add1",
// header: "Bed Count",style:"right"
//),
grid.Column("",
header: "Actions",
format: #<text>
#Html.ActionLink("Edit", "EditPatient", new { id = item.PatientID }, htmlAttributes: new { #class = "link" })
|
#Html.ActionLink("Delete", "PatientList", new { id = item.PatientID },
htmlAttributes: new { #class = "link", onclick = "return confirm('Are you sure you wish to delete this record?');" })
</text>
)
})
</div>
**controller**
public ActionResult PatientList(int page = 1, string sort = "Dr_Id", string sortDir = "ASC", int id = 0)
{
if (id != 0)
{
bool isDelete = false;
isDelete = rdm_Patient.DeletePatient(id);
return View(GetPatient(page, sort, sortDir));
}
else
{
return View(GetPatient(page, sort, sortDir));
}
}
private PatientPageViewModel GetPatient(int page = 1, string sort = "Dr_Id", string sortDir = "ASC")
{
const int patientPerPage = 5;
var numPatient = rdm_Patient.CountPatient();
sortDir = sortDir.Equals("desc", StringComparison.CurrentCultureIgnoreCase) ? sortDir : "asc";
var validColumns = new[] { "PatientID", "PatientName" };
if (!validColumns.Any(c => c.Equals(sort, StringComparison.CurrentCultureIgnoreCase)))
sort = "PatientID";
var doctors = rdm_Patient.getpatientpage(page, patientPerPage, "it." + sort + " " + sortDir);
var data = new PatientPageViewModel()
{
numberOfPatient = numPatient,
patientPerPage = patientPerPage,
Patient = doctors,
};
return data;
}
As I understand of your question you need filtering in your WebGrid that doesn’t include any kind of tool to perform it. So, you have to do it manually.
You should take into account the following points:
Firstly, include a form in the View where the query criteria is collected in order to send it to the controller.
Secondly, prepare the Controller so it can receive this criteria and make it reach the Model.
Thirdly, in the Model, simply apply this criteria when counting the total amount of rows, and when obtaining the data to be displayed in the grid page.
Jose M. Aguilar in his post describes all steps which can help you to design your view and controller.
Index.cshtml:
#model MvcApplication1.Models.Employee
#{
ViewBag.Title = "Index";
}
<h2>Index</h2>
<table>
<tr>
<td>
#Html.DropDownList("lstdepartment", Model.Department_List)
</td>
</tr>
<tr>
<td>
<div id="EmployeeViewGrid">
#Html.Partial("EmployeeView",Model.Employee_Grid)
</div>
</td>
</tr>
</table>
<script type="text/javascript">
$('#lstdepartment').change(function (e) {
e.preventDefault();
var url = '#Url.Action("Filter")';
$.get(url, { department: $(this).val() }, function (result) {
debugger;
$('#EmployeeViewGrid').html(result);
});
});
</script>
Partial view:
#model List< MvcApplication1.Models.Employee>
#{
ViewBag.Title = "EmployeeView";
}
<h2>EmployeeView</h2>
<div id="gridposition" style="overflow: scroll; height: 300px; overflow-x: hidden;">
#{
var grid1 = new WebGrid(source: Model, canPage: true, rowsPerPage: 5, ajaxUpdateContainerId: "gridContent");
#grid1.GetHtml(mode: WebGridPagerModes.All, tableStyle: "webGrid",
headerStyle: "header",
alternatingRowStyle: "alt",
selectedRowStyle: "select",
rowStyle: "description",
htmlAttributes: new { id = "positionGrid" },
fillEmptyRows: false,
columns: grid1.Columns(
grid1.Column("EmployeeId", header: "EmployeeId"),
grid1.Column("EmpName", header: "EmpName"),
grid1.Column("Age", header: "Age"),
grid1.Column("Department", header: "Department"),
grid1.Column("Salary", header: "Salary")))
}
</div>
Controller:
using System;
using System.Collections.Generic;
using System.Data;
using System.Data.Entity;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using MvcApplication1.Models;
namespace MvcApplication1.Controllers
{
public class EmployeeController : Controller
{
private EmployeeDatabaseEntities1 db = new EmployeeDatabaseEntities1();
//
// GET: /Employee/
public ActionResult Index()
{
Employee _model = new Employee();
//_model.Employee_Grid = db.tbl_Employee.ToList();
var departmentlist = db.tbl_department.ToList();
_model.Department_List = (from d in departmentlist
select new SelectListItem
{
Value = d.department_id.ToString(),
Text = d.department_name
}).ToList();
var qq = (from e in db.tbl_Employee
join d in db.tbl_department on e.Department_id equals d.department_id
select new Employee
{
Department_id=e.Department_id,
EmployeeId=e.EmployeeId,
EmpName=e.EmpName,
Age=e.Age,
Department=d.department_name
}).ToList();
_model.Employee_Grid = qq;
return View("Index", _model);
}
public ActionResult Filter(string department)
{
int? department_id = Convert.ToInt32(department);
var qq = (from e in db.tbl_Employee
join d in db.tbl_department on e.Department_id equals d.department_id
where e.Department_id == department_id
select new Employee
{
Department_id = e.Department_id,
EmployeeId = e.EmployeeId,enter code here
EmpName = e.EmpName,
Age = e.Age,
Department = d.department_name
}).ToList();
return PartialView("EmployeeView",qq);
}
}
}