How will i bind Web Grid in MVC 3 from DataSet - asp.net-mvc-3

#{
var grid = new WebGrid(source: ViewBag.AllUsers,//in view Bag we have dataset to bind
rowsPerPage: 10);
}
#grid.GetHtml(
tableStyle: "gridtable",
alternatingRowStyle: "even",
columns: grid.Columns(
grid.Column("UserId", "Id"),
grid.Column("userName", "Name"),
grid.Column("City", "City"),
grid.Column("Designation","Designation"),
grid.Column("sal","Salary")
)
)
)

In your controller put the code like this
[HttpGet]
public ActionResult View(Modelclass viewmodel)
{
List<Modelclass> employees = new List<Modelclass>();
DataSet ds = viewmodel.GetAllAuthors();
var empList = ds.Tables[0].AsEnumerable().Select(dataRow => new Modelclass{
AuthorId = dataRow.Field<int>("AuthorId"),
Fname = dataRow.Field<string>("FName"),
Lname = dataRow.Field<string>("Lname")
});
var list = empList.ToList();
return View(list);
}
And in view
#gd.GetHtml(tableStyle: "table",
columns: gd.Columns(
gd.Column("AuthorId", "AuthorId"),
gd.Column("Fname", " Fname"),
gd.Column("Lname", "Lname", style: "description")
))

Related

MVC ListBox Selected Values

New to MVC and Stackoverflow so sorry for not having enough reputation to post images...
Trying to render a ListBox with pre selected values
My SQL Database:
http://i.imgur.com/bcdXyqE.png
My Entity Framework
http://i.imgur.com/wYWXuAq.png
My Controller
public ActionResult AccessRights(int id)
{
var user = db.User.Find(id);
var roles = db.Role;
var newList = new List<SelectListItem>();
foreach (var role in roles)
{
newList.Add(
new SelectListItem()
{
Value = role.Id.ToString(),
Text = role.RoleName,
Selected = user.Role.Contains(role)
}
);
}
ViewBag.x = new SelectList(newList, "Value", "Text");
ViewBag.Roles = new SelectList(db.Role, "Id", "RoleName", user.Role);
return View(user);
}
My View
<p>try1:</p>
#Html.ListBox("Roles", null, new { #class = "form-control", #size = 6, #style = "height: initial" })
<p>try2:</p>
#Html.ListBox("x", null, new { #size = 6, #style = "height: initial" })
Non of the 2 tries renders with pre selected values?
got it working.
public ActionResult AccessRights(int id)
{
var user = db.User.Find(id);
IEnumerable<SelectListItem> roles = db.Role.Select(c => new SelectListItem{ Value = c.Id.ToString(), Text = c.RoleName, Selected = true});
var rolesSelected = new int[user.Role.Count];
var i = 0;
foreach (var role in user.Role)
{
rolesSelected[i] = role.Id;
i++;
}
ViewBag.Roles = roles.ToList();
ViewBag.RolesSelected = rolesSelected;
return View(user);
}
#Html.ListBox("RolesSelect", new MultiSelectList(ViewBag.Roles, "Value", "Text", ViewBag.RolesSelected), new { #class = "form-control", #size = 6, #style = "height: initial" })

the paging of Grid.MVC not work

Im using Grid.MVC in my MVC web application
When test it in a blank page with index controller it works successfully with pagination and filtration.
The Problem accrue when i put it in my project
the steps that i do that i make ajax request (because i don't need to reload the page) to method and return a partial view that contains the result of the search by the Grid.Mvc the result and number of pages return successfully but when i press to next page or filter it doesn't work.
Code:
View:
#using (Ajax.BeginForm("Search", "Home",
new AjaxOptions
{
HttpMethod = "POST",
InsertionMode = InsertionMode.Replace,
UpdateTargetId = "SearchResult"
})){
#Html.DropDownList("Province", "Province")
#Html.DropDownList("Cities", "Cities")
<span>price from :</span> <input type="text" name="Pricefrom" />
<span>to :</span> <input type="text" name="Priceto" />
<input type="submit" value="Search" /> }
Search Controller :
[HttpPost]
public ActionResult Search(int? page , int Province = 0, int Cities = 0, int Pricefrom = 0, int Priceto = 0)
{
var ads = db.Ad.Where(a => (Cities == 0 || a.CityId == Cities) &&
(Province == 0 || a.Cities.ProvinceId == Province)&&
(Pricefrom == 0 || a.Price >= Pricefrom)&&
(Priceto == 0 || a.Price <= Priceto)).OrderBy(a => a.AdDate).ToList();
return PartialView("_Search", ads);
}
PartialView:
#using GridMvc.Html
#model IEnumerable<Semsark.Areas.Backend.Models.Ad>
<div>
#Html.Grid(Model).Columns(columns =>
{
columns.Add(c => c.Id).Titled("ID");
columns.Add(c => c.AdTitle).Titled("title");
columns.Add(c => c.AdBody).Titled("body");
}).WithPaging(2).Sortable(true)
</div>
scripts and styles in the View index.cshtml :
<head>
<meta name="viewport" content="width=device-width" />
<link href="#Url.Content("~/Content/Gridmvc.css")" rel="stylesheet" />
<script src="#Url.Content("~/Scripts/gridmvc.min.js")"></script>
<script src="~/Scripts/gridmvc.lang.ru.js"></script>
<title>Index</title>
Thanks in advance for any help,
#*Webgrid using Paging in mvc 4.
View Page **.cshtml** *#
#model MvcPopup.Models.PagedEmployeeModel
#{
//ViewBag.Title = "SearchEmployee";
Layout = null;
}
#{
WebGrid grid = new WebGrid(rowsPerPage: Model.PageSize);
grid.Bind(Model.Employee,
autoSortAndPage: false,
rowCount: Model.TotalRows
);
}
#grid.GetHtml(
fillEmptyRows: false,
alternatingRowStyle: "alternate-row",
headerStyle: "grid-header",
footerStyle: "grid-footer",
mode: WebGridPagerModes.All,
firstText: "<< First",
previousText: "< Prev",
nextText: "Next >",
lastText: "Last >>",
columns: new[] {
grid.Column("Name",
header: "Name",
format: #<text>
#Html.ActionLink((string)item.Name, "ViewEmployeeDetail", new { id = item.id }, new { #class = "viewDialog" })</text>
),
grid.Column("Department"),
grid.Column("City"),
grid.Column("State"),
grid.Column("Country",
header: "Country"
),
grid.Column("Mobile"),
grid.Column("",
header: "Actions",
format: #<text>
#Html.ActionLink("Edit", "EditEmployee", new { id = item.id }, new { #class = "editDialog" })
|
#Html.ActionLink("Delete", "Delete", new { id = item.id }, new { #class = "confirmDialog"})
</text>
)
})
#*-----------------------------------
Model folder under modelservices.cs file
=================================*#
public IEnumerable<Employee> GetEmployeePage(int pageNumber, int pageSize, string searchCriteria)
{
if (pageNumber < 1)
pageNumber = 1;
return db.Employees
.OrderBy(m =>m.Name)
.Skip((pageNumber - 1) * pageSize)
.Take(pageSize)
.ToList();
}
public int CountAllEmployee()
{
return db.Employees.Count();
}
public class PagedEmployeeModel
{
public int TotalRows { get; set; }
public IEnumerable<Employee> Employee { get; set; }
public int PageSize { get; set; }
}
#*Controller folder under create file like employeecontroller.cs *#
using MvcPopup.Models;
using System.Globalization;
using System.Text;
namespace MvcPopup.Controllers
{
public class EmployeeController : Controller
{
//
// GET: /Employee/
ModelServices mobjModel = new ModelServices();
public ActionResult Index()
{
return View();
}
public ActionResult SearchEmployee(int page = 1, string sort = "name", string sortDir = "ASC")
{
const int pageSize = 5;
var totalRows = mobjModel.CountAllEmployee();
sortDir = sortDir.Equals("desc", StringComparison.CurrentCultureIgnoreCase) ? sortDir : "asc";
var validColumns = new[] { "id", "name", "department", "country" };
if (!validColumns.Any(c => c.Equals(sort, StringComparison.CurrentCultureIgnoreCase)))
sort = "id";
var employee = mobjModel.GetEmployeePage(page, pageSize, "it." + sort + " " + sortDir);
var data = new PagedEmployeeModel()
{
TotalRows = totalRows,
PageSize = pageSize,
Employee = employee
};
return View(data);
}
------------------------
Have you tried to pass through an IQueryable list instead of an IEnumerable? According to the documentation, Gridmvc.Html requires an IQueryable for paging. There are some subtle differences between IQueryable and IEnumerable that might make a difference here.
These scripts are needed for paging:
"~/Scripts/GridMvc/URI.js"
"~/Scripts/GridMvc/gridmvc.min.js"
"~/Scripts/GridMvc/gridmvc-ext.js"

How to use foreach inside webgrid + MVC 3

I have webgrid as below in MVC:how to show list of values in a single row in column in webgrid.I am using foreach inside webgrid column but it is unrecognized
Col1 Col2 Col3
---------------
1 | zzz | t
| xxx |
| yyy |
---------------
2 | aaa | P
| bbb |
| ccc |
Above grid is just sample Example..i want to show data.
In 2nd column i want to show list of values in single row.Below code I tried,But i get Error foreach is invalid in webgrid.
In Model:
public class Employee
{
public string EmployeeId { get; set; }
public string EmployeeName { get; set; }
public string RowId { get; set; }
public string Error { get; set; }
public List<string> tbldata { get; set; }
public List<Employee> lstEmp { get; set; }
}
In Controller:
public ActionResult Index()
{
Employee emp = new Employee();
List<string> tbldata3 = new List<string>();
tbldata3.Add("xxx");
tbldata3.Add("yyy");
tbldata3.Add("zzz");
List<string> tbldata1 = new List<string>();
tbldata1.Add("gggh");
tbldata1.Add("hhhh");
tbldata1.Add("ffff");
List<string> tbldata2 = new List<string>();
tbldata2.Add("ppp");
tbldata2.Add("oooo");
tbldata2.Add("iii");
List<Employee> lstempo = new List<Employee>();
lstempo.Add(new Employee { EmployeeId = "100", EmployeeName = "aaa", RowId = "111", Error = "3434", tbldata = tbldata1 });
lstempo.Add(new Employee { EmployeeId = "101", EmployeeName = "BB", RowId = "222", Error = "6767", tbldata = tbldata2 });
lstempo.Add(new Employee { EmployeeId = "102", EmployeeName = "ccc", RowId = "333", Error = "898", tbldata = tbldata3 });
emp.lstEmp = lstempo;
return View(emp);
}
In View:
#{
var grid = new WebGrid(source: Model.lstEmp,
canSort: true,
rowsPerPage: 10,
ajaxUpdateContainerId: "grdCurrentReqDetails"
);
}
#grid.GetHtml(
tableStyle: "webGrid",
headerStyle: "gridHead",
alternatingRowStyle: "alt",
columns: grid.Columns
(
grid.Column("EmployeeId", header: "EmployeeId"),
grid.Column("EmployeeName", header: "EmployeeName"),
grid.Column("RowId", header: "RowId"),
grid.Column("Error", header: "Error"),
grid.Column("Checks", format: (item) => { return new HtmlString(
"<table><tr><td>"+
foreach(var t in item.tbldata)
{
t.ToString();
}
+"</td></tr></table>"
); })
)
)

Bind Telerik DDL

I am trying to bind a Telerik DropDownList.
View Code:
<div>#( Html.Telerik().DropDownList()
.Name("ddlCounty")
.HtmlAttributes(new { style = "width:200px;" })
.SelectedIndex(0)
.BindTo(new SelectList((IEnumerable<MvcNew.Models.tbl_Country>)ViewData["ListCountries"], "Value", "Text")) )
</div>
Controller Code:
List<SelectListItem> lst_Country = new List<SelectListItem>();
var Countries = (from m in DBContext.tbl_Countries
select new SelectListItem{ Text = m.Country__Name.ToString(), Value = m.Country_ID.ToString() });
ViewBag.ListCountries = new SelectList(Countries);
return View();
I am getting the below error
Unable to cast object of type 'System.Web.Mvc.SelectList' to type 'System.Collections.Generic.IEnumerable`1[MvcNew.Models.tbl_Country]'.
I have changed a code like this and it's worked
var clientIDs = DBContext.tbl_Countries
List<SelectListItem> items = new List<SelectListItem>();
foreach (var t in clientIDs)
{
SelectListItem s = new SelectListItem();
s.Text = t.Country__Name.ToString();
s.Value = t.Country__Name.ToString();
items.Add(s);
}
ViewBag.ListCountries = items;

MVC3 razor Webgrid -retaining page after a delete

On my MVC3 razor page, I am using a webgrid to show a list of approx 100 plus records.
I am setting a page size to 10 and paging and sorting is working fine. My only issue here is on my page I have a "delete" hyperlink on the webgrid. When I click "delete", it will delete the record and reload the page. But when reloading the page it goes back to the page1
For instance, if I am on page4 and I click "delete", it deletes that record and comes to the page1, but I want to remain in page4 itself. Any suggestions on how to achieve this.
public ViewResult Index(int? page, string sort)
{
var startPage = 0;
if (page.HasValue && page.Value > 0)
{
startPage = page.Value - 1;
}
vm.Employees = GetAllEmployeeData(startPage, vm.PageSize, sort);
vm.TotalRecords = context.TableEmployee.Count();
return View(vm);
}
public IEnumerable<Employees> GetAllEmployeeData(int page, int records, string sort)
{
IEnumerable<Employees> EmployeeData = null;
EmployeeData = context.TableEmployee.Where(e => e.IsActivated == true)
.Select(e => new Employees{ EmpID = e.EmpID, Name= e.Name, Joiningdate = e.Joiningdate , Department = e.DeptName}).AsEnumerable<Employees>();
switch (sort)
{
case "Department":
EmployeeData = EmployeeData .OrderBy(r => r.Department);
break;
case "JoiningDate":
EmployeeData = EmployeeData .OrderBy(r => r.JoiningDate);
break;
default:
EmployeeData = EmployeeData .OrderBy(r => r.Name);
break;
}
EmployeeData = EmployeeData .Skip(page * records).Take(records).ToList();
return EmployeeData ;
}
public ActionResult DeleteSelectedEmployee(int empId)
{
ContentsViewModel model = new ContentsViewModel();
int timelineItemId = 0;
EmployeeData E = context.TableEmployee.Find(empId);
context.TableEmployee.Remove(E);
context.SaveChanges();
return RedirectToAction("Index");
}
Here is my webgrid
#{var webgrid = new WebGrid(canPage: true, rowsPerPage: Model.PageSize, canSort: true, ajaxUpdateContainerId: "grid");
webgrid.Bind(Model.Employees, rowCount: Model.TotalRecords, autoSortAndPage: false);
webgrid.Pager(WebGridPagerModes.Numeric);
#webgrid.GetHtml(tableStyle: "webgridTable", htmlAttributes: new { id = "grid" },
columns: webgrid.Columns(
webgrid.Column("Name", "Name"),
webgrid.Column("Department", "Department"),
webgrid.Column("JoiningDate", "Join Date", format: #<text>#item.JoiningDate.ToString("dddd, MMMM d, yyyy")</text>),
webgrid.Column(header: "Action", format: (item) => Html.ActionLink("Edit", "Edit", new { empId = item.EmpID })),
webgrid.Column(format: (item) => Html.ActionLink("Delete", "Delete Record", new { empId = item.EmpID }))
));
}

Resources