MVC Web grid with column with line break

Controler::
__________________________
[HttpGet]
public ActionResult EmployeeTaskReport()
{
using (DataAccessLayer.DatabaseContext db = new DataAccessLayer.DatabaseContext())
{
int UserLoginID = UserRepository.GetLoginUserID();
var UserTaskList = db.TaskMasters.Where(_ => _.LoginID.Value.Equals(UserLoginID)).ToList();
ViewBag.TaskStatus = db.TaskStatusMasters.ToList();
ViewBag.SchoolName = db.SchoolMasters.ToList();
ViewBag.ProjectName = db.ProjectMasters.ToList();
//return View(UserTaskList);

List lstERTVM = new List();
foreach (TaskMaster tm in UserTaskList)
{
lstERTVM.Add(new EmployeeTaskReportViewModel { TMaster = tm });
}
return View(lstERTVM);

}
}

ViewModel____________________________
public class EmployeeTaskReportViewModel
{
public TaskMaster TMaster { get; set; }

public string TaskReportDetail;

public string _TaskReportDetail
{
get {
TaskReportDetail += “TaskName: ” + Convert.ToString(this.TMaster.TaskName) + “\r\n”;
TaskReportDetail += “SchoolName: ” + (this.TMaster.SchoolMaster == null ? “” : Convert.ToString(this.TMaster.SchoolMaster.SchoolName)) + “\r\n”;
TaskReportDetail += “ProjectName: ” + (this.TMaster.ProjectMaster == null ? “” : Convert.ToString(this.TMaster.ProjectMaster.ProjectName)) + “\r\n”;
return TaskReportDetail;
}
set { TaskReportDetail = value; }
}

}
Web grid in View______________

@{
WebGrid grid = new WebGrid(Model);
@grid.GetHtml(
tableStyle: “grid”,
fillEmptyRows: false,
headerStyle: “gvHeading”,
alternatingRowStyle: “gvAlternateRow”,
rowStyle: “gvRow”,
footerStyle: “gvFooter”,

mode: WebGridPagerModes.All,
firstText: “<< First",
previousText: "”,
lastText: “Last >>”,
columns: new[] {

grid.Column(“Sr.No.”, format: item => item.WebGrid.Rows.IndexOf(item)+1),
grid.Column(“Review”, format: (item) =>
{
string review = item._TaskReportDetail ?? “”;
return new HtmlString(review.Replace(“\r\n”, “
“));
}),

grid.Column(“ContactusId”, header: “Action”, canSort:false,

format: @

)
})
}

Advertisements

MVC DELETE CONFIRMATION

Razer View:
@{
ViewBag.Title = “Home Page”;
}

.dialog_css
{
border: 0px none !important;
-moz-box-shadow: 1px 2px 4px 2px rgb(136, 136, 136);
-webkit-box-shadow: 1px 2px 4px 2px rgb(136, 136, 136);
box-shadow: 3px 6px 8px rgb(136, 136, 136);
}

Item Name Delete
Laptop Delete
Mobile Delete
ipad Delete

@section Scripts {
@Scripts.Render(“~/bundles/jqueryval”)

http://@Url.Content(
http://@Url.Content(

// delete Link
$(‘.delete-link’).click(function () {
var deleteLinkObj = $(this); //for future use

$(“#delete-dialog”).dialog({
title: “Confirmation”,
buttons: {
Continue: function () {
$.post(deleteLinkObj[0].href, function (data) { //Post to action
if (data.Status == ‘true’) {
var tr = deleteLinkObj.parents(‘tr:first’);
tr.hide(‘fast’); //Hide Row
}
else {
//(optional) Display Error
}
});
$(this).dialog(‘close’);
},
Close: function () {
$(this).dialog(‘close’);
}
},
dialogClass: ‘dialog_css’,
width: 400,
closeOnEscape: false,
draggable: false,
resizable: false,
modal: true
});
return false; // prevents the default behaviour

});

}

Controller:
[HttpPost]
public ActionResult Delete(int id)
{
try
{
return Json(new { Status = “true” });
}
catch
{
return Json(new { Status = “false” });
}
}

MVC partial view grid with working paging and shorting

#region EmployeeWorkReport Controler Page Coding
[HttpGet]
public ActionResult EmployeeWorkReport()
{
using (DataAccessLayer.DatabaseContext db = new DataAccessLayer.DatabaseContext())
{
ViewBag.LoginID = new SelectList(db.Employees.Where(_ => _.status.Equals(“1”) && _.Role.Equals(“Employee”)).Select(_ => new { LoginID = _.LoginID, UserName = _.Firstname + “” + _.Lastname + “-” + _.EmployeeID}).ToList(), “LoginID”, “UserName”);
ViewBag.ProjectID = new SelectList(db.ProjectMasters.Where(_ => _.Status.Equals(“1”)).ToList(), “ID”, “ProjectName”);
}
return View();
}

[HttpGet]
public ActionResult EmployeeWorkReportFilter(string EmpLoginID, string ProjectID, string WorkDateFrom, string WorkDateTo)
{
//EmployeeWorkReportFilter
using (DataAccessLayer.DatabaseContext db = new DataAccessLayer.DatabaseContext())
{
int EmpID = 0, Projid = 0;
DateTime _fromDate = DateTime.Now.Date; DateTime _ToDate = DateTime.Now.Date;
bool isFromDateValid = false, istoDateValid = false;
List partialdata = db.EmployeeDailyWorks.ToList();

// Filter For Employee
if (int.TryParse(EmpLoginID, out EmpID))
{
partialdata = partialdata.Where(_ => _.LoginID.Value.Equals(EmpID)).ToList();
}
// Filter for Project
if (int.TryParse(ProjectID, out Projid))
{
partialdata = partialdata.Where(_ => _.ProjectID != null && _.ProjectID.Value.Equals(Projid)).ToList();
}
// Filter For date
if (!string.IsNullOrEmpty(WorkDateFrom))
{
if (DateTime.TryParse(WorkDateFrom, out _fromDate))
{
isFromDateValid = true;
}
else
{
ModelState.AddModelError(string.Empty, “Please enter valid date”);
return View();
}

}
if (!string.IsNullOrEmpty(WorkDateTo))
{
if (DateTime.TryParse(WorkDateTo, out _ToDate))
{
istoDateValid = true;
}
else
{
ModelState.AddModelError(string.Empty, “Please enter valid date”);
return View();
}

}

if (isFromDateValid && istoDateValid)
{
if (_fromDate > _ToDate)
{
ModelState.AddModelError(string.Empty, “Please enter valid date”);
return View();
}
else
{
partialdata = partialdata.Where(_ => _.WorkDate >= _fromDate && _.WorkDate _.WorkDate >= _fromDate).ToList();
}
else if (istoDateValid)
{
partialdata = partialdata.Where(_ => _.WorkDate <= _ToDate).ToList();
}

if (partialdata.Any())
{
ViewBag.employeemaster = db.Employees.ToList();
ViewBag.projectmaster = db.ProjectMasters.ToList();
ViewBag.SchoolMaster = db.SchoolMasters.ToList();
ViewBag.TaskMaster = db.TaskMasters.ToList();
}

return PartialView("EmployeeWorkReportFilter", partialdata);
}

}
#endregion

________________________________View page codng ___________
@model IEnumerable
@{
ViewBag.Title = “EmployeeWorkReport”;
Layout = “~/Views/Shared/_LayoutAdmin.cshtml”;
}
http://~/Scripts/jquery-2.1.4.min.js
http://~/Scripts/jquery.validate.min.js
http://~/Scripts/jquery.validate.unobtrusive.min.js

.

@Html.DropDownList(“LoginID”, ViewBag.LoginID as SelectList, “Select Employee”, new { @class = “form-control” })
@Html.DropDownList(“ProjectID”, ViewBag.ProjectID as SelectList, “Select Project”, new { @class = “form-control” })

@Html.Hidden(“hiddenhref”)
@*@Html.Action(“EmployeeWorkReportFilter”)*@

@System.Web.Optimization.Scripts.Render(“~/Scripts/jquery-1.12.4.js”)
@System.Web.Optimization.Scripts.Render(“~/Scripts/jquery-ui-1.12.0.js”)
@System.Web.Optimization.Styles.Render(“~/Content/themes/base/jquery-ui.css”)

$(‘input[type=datetime]’).datepicker({
inline: true,
dateFormat: “yy-MM-dd”,
changeMonth: true,
changeYear: true,
yearRange: “-60:+0”
});

function callreport() {
var _EmpLoginID = $(“#LoginID”).val();
var _ProjectID = $(“#ProjectID”).val();
var _WorkDateFrom = $(“#WorkDateFrom”).val();
var _WorkDateTo = $(“#WorkDateTo”).val();
var url = “/AdminReport/EmployeeWorkReportFilter”;
$.get(url, { EmpLoginID: _EmpLoginID, ProjectID: _ProjectID, WorkDateFrom: _WorkDateFrom, WorkDateTo: _WorkDateTo }, function (response) {

/*—–Code Start for partial view webgrid pagination to work with main view and on click of pagination grid open in parent view page———*/
var $response = $(response);
$response.html($response.html().replace(‘/AdminReport/EmployeeWorkReportFilter’, ‘/AdminReport/EmployeeWorkReport’));
/*——Code End——–*/
$(“#employeePartalListGrid”).html($response);
});
}

.gridTable {
margin: 5px;
padding: 10px;
border: 1px #c8c8c8 solid;
border-collapse: collapse;
min-width: 550px;
background-color: #fff;
color: #fff;
width: 100%;
}

.gridHead th {
font-weight: bold;
background-color: #030D8D;
color: #fff;
padding: 10px;
text-align: left;
}

.gridHead a:link, .gridHead a:visited, .gridHead a:active, .gridHead a:hover {
color: #fff;
}

.gridHead a:hover {
text-decoration: underline;
}

.gridTable tr.gridAltRow {
background-color: #efeeef;
}

.gridTable tr:hover {
background-color: #f6f70a;
}

.gridAltRow td {
padding: 10px;
margin: 5px;
color: #333;
text-align: left;
}

.gridRow td {
padding: 10px;
color: #333;
text-align: left;
}

.gridFooter td {
padding: 10px;
color: #ffffff;
font-size: 12pt;
text-align: center;
background-color: #228B22;
}

.gridFooter a {
font-weight: bold;
color: blue;
border: 2px #f00 solid;
}

_____________________________Partail view grid coding ____________
@model List

@{
ViewBag.Title = “EmployeeWorkReportFilter”;

}

@{

var grid = new WebGrid(source: Model, canPage: true, canSort: true, rowsPerPage: 10, ajaxUpdateContainerId: “grid”);

@grid.GetHtml(mode: WebGridPagerModes.All,
tableStyle: “gridTable”,
headerStyle: “gridHead”,
footerStyle: “gridFooter”,
rowStyle: “gridRow”,
alternatingRowStyle: “gridAltRow”,
htmlAttributes: new { id = “grid” },
fillEmptyRows: false,
columns: new[]{
grid.Column(“Sr.No.”, format: item => item.WebGrid.Rows.IndexOf(item) + 1),
grid.Column(“Name”, format: item => item.Employee == null ? “” : item.Employee.Firstname + “” + item.Employee.Lastname + “-” + item.Employee.EmployeeID),
grid.Column(“WorkDate”, format: item => @Convert.ToDateTime(item.WorkDate).ToString(“yyyy MMM dd”)),
grid.Column(“ProjectName”, format: item => item.ProjectMaster == null ? “” : item.ProjectMaster.ProjectName),
grid.Column(“SchoolName”, format: item => item.SchoolMaster == null ? “” : item.SchoolMaster.SchoolName),
grid.Column(“TaskName”, format: item => item.TaskMaster == null ? “” : item.TaskMaster.TaskName),
grid.Column(“DailyWorkDetail”, header: “WorkDetail”),
grid.Column(“Status”,format: (item) =>
{
if (item.Status == “1”)
{

return Html.Raw(“Active”);
}
else
{

return Html.Raw(“Inactive”);
}
}
)}

)
}

@*/*—–Code Start for partial view webgrid pagination to work with main view and on click of pagination grid open in parent view page———*/*@
@System.Web.Optimization.Scripts.Render(“~/Scripts/jquery-1.12.4.js”)

$(‘th a’).click(function () {
var form = $(‘#gridposition’);
form.attr(“action”, this.href);
$(this).attr(“href”, “javascript:”);
form.submit();

});

@*/*——Code End——–*/*@

Mysql data backup restore from corrupted system

Get mysql datafiles and restore on new system.

http://stackoverflow.com/questions/10680261/restore-mysql-database-folder-from-a-recovered-hard-disk

1:: Find Data Folder of mysql server
You can try this-in All programm=> MySql Server => open CMD

mysql> select @@datadir;

ex:: C:\ProgramData\MySQL\MySQL ser 5.1\Data\

2::

Go over to the target computer, Open System Services.
(Type services.msc at the Windows menu “Search Program and files” entry box

3::

On the right panel of the Services window, scroll along the list and look for the name “MYSQL“.
Select MYSQL and right mouse click and click . Once it has stopped, you will it’s status become blank instead of .

4::
Similarly look for the location of the data folder. Once you located it,
I recommend you back up the folder or just rename it.
Paste over the folders and ibdata file you have copied from the source computer to the data folder.

5::
Go back to the Services window and select back MYSQL.
Right mouse click on it and click to resume the MYSQL service.

6::
Open MYSQL administrator and log on to your database
server and you should be able to see your transferred database together with their data.

@URL.Action on ancher click and dynamic dropdown bind.

Controler Code:

ViewBag.StatusMaster = new SelectList(StatusMaster, “ID”, “TaskStatus”);

 

View Page code:

@SelectedSchoolName Unmapped projects
— @if (SelectedSchoolID > 0)
— {

    — @{int counter = 0;}
    — @foreach (var item in UnmappedProjectList)
    — {
    — counter=item.ID;

  1. @item.ProjectName
    —-
    — @Html.DropDownList(string.Format(“StatusMaster_{0}”, counter), ViewBag.StatusMaster as SelectList, “Select Status”, new { @class = “form-control” })
    Map

  2. — }

— }

Script Code:

https://ajax.googleapis.com/ajax/libs/jquery/1.12.4/jquery.min.js

$(“.ProjectMapAncher”).click(function (evt) {
var suffixControl_id = $(this).attr(‘data-id’);
var fakedUri = $(“#ProjectMapAncher_” + suffixControl_id).prop(“href”);
var Remarksvalue = $(“#Remarks_” + suffixControl_id).val();
var TaskStatusValue = $(‘#StatusMaster_’ + suffixControl_id).val();
if (TaskStatusValue == “”) {
$(“#dialog-text_” + suffixControl_id).html(“Select Status”);
return false;
}
else {
var uri = fakedUri.replace(“EnterRemarksValueHere”, Remarksvalue).replace(“EnterTaskStatusValueHere”, TaskStatusValue);
$(this).attr(“href”, uri);
}

});

Passing Data Between Current and Subsequent Request-MVC

Use TempData instead of ViewData/ViewBag to store data that should persist after redirect. ViewData/ViewBag allow to pass value from controller to view.

You can use TempData.You can pass every types of data between to action, whether they are in same controller or not. Your code should be something like it:

 public ActionResult GetMDN(string msisdn)
    {
        int sngid=10;

        TempData["ID"] = sngid;

        return RedirectToAction("IIndex");
    }

    public ActionResult IIndex()
    {

        int id = Convert.ToInt32(TempData["ID"]);// id will be 10;
    }

ASP.NET MVC offers us three options – ViewData, ViewBag and TempData for passing data from controller to view and in next request. ViewData and ViewBag are almost similar and TempData performs additional responsibility. Let’s discuss or get key points on those three objects:

Similarities between ViewBag & ViewData:

  1. Helps to maintain data when you move from controller to view.
  2. Used to pass data from controller to corresponding view.
  3. Short life means value becomes null when redirection occurs. This is because their goal is to provide a way to communicate between controllers and views. It’s a communication mechanism within the server call.

Difference between ViewBag & ViewData:

  1. ViewData is a dictionary of objects that is derived from ViewDataDictionary class and is accessible using strings as keys.
  2. ViewBag is a dynamic property that takes advantage of the new dynamic features in C# 4.0.
  3. ViewData requires typecasting for complex data type and check for null values to avoid error.
  4. ViewBag doesn’t require typecasting for complex data type.

ViewBag & ViewData Example:

public ActionResult Index()
{
    ViewBag.Name = "Monjurul Habib";
    return View();
}
public ActionResult Index()
{
    ViewData["Name"] = "Monjurul Habib";
    return View();
}

In View:

@ViewBag.Name 
@ViewData["Name"]

TempData:

TempData is also a dictionary derived from TempDataDictionary class and stored in short lives session and it is a string key and object value. The difference is the life cycle of the object. TempData keeps the information for the time of an HTTP Request. This mean only from one page to another. This also works with a 302/303 redirection because it’s in the same HTTP Request. It helps to maintain data when you move from one controller to other controller or from one action to other action. In other words, when you redirect, “Tempdata” helps to maintain data between those redirects. It internally uses session variables. Temp data use during the current and subsequent request only means it is used when you are sure that next request will be redirecting to next view. It requires typecasting for complex data type and check for null values to avoid error. It is generally used to store only one time messages like error messages, validation messages.

public ActionResult Index()
{
  var model = new Review()
            {
                Body = "Start",
                Rating=5
            };
    TempData["ModelName"] = model;
    return RedirectToAction("About");
}
public ActionResult About() 
{     
    var model= TempData["ModelName"];     
    return View(model); 
}

The last mechanism is the Session which works like the ViewData, like a Dictionary that takes a string for key and object for value. This one is stored into the client Cookie and can be used for a much more long time. It also needs more verification to never have any confidential information. Regarding ViewData or ViewBag, you should use it intelligently for application performance. Because each action goes through the whole life cycle of regular ASP.NET MVC request. You can use ViewData/ViewBag in your child action, but be careful that you are not using it to populate the unrelated data which can pollute your controller.