razor syntax, using input to run database query - c#

I'm creating a simple webpage with Razor syntax and I have a little trouble with using buttons forms and input; how do I attach
db.Execute("exec dbo.deleteProject #0", #item.Key_Project);
to the input in last column of webgrid (via action or onclick)?
#{ //layout etc
var db = Database.Open("defaultConnection");
var ProjectNameGrid = new WebGrid(source: db.Query(SelectAllProjectKeysNamesStates),
canSort: false);}
#ProjectNameGrid.GetHtml(
columns: ProjectNameGrid.Columns(
ProjectNameGrid.Column("Key_Project", "ID", style: "smallColumn"),
ProjectNameGrid.Column("ProjectName", "Project", style: "LongColumn"),
ProjectNameGrid.Column("ProjectStartDate", "Starting date"),
ProjectNameGrid.Column("ProjectEndDate", "Ending date"),
ProjectNameGrid.Column("IsActive", "Active", style: "smallColumn"),
ProjectNameGrid.Column("Key_Project", "", format:
#<input type="submit" method="post" action="" value="delete" />) ),
tableStyle: "grid",
headerStyle: "head",
alternatingRowStyle: "alt")

use Razor ActionLink Like Bellow:
#Html.ActionLink("Text", "Action", "Controller", new {param1 = val1, param2 = val2}, null)

Related

How to use a drop down list from model in WebGrid MVC C#

What is the best or easiest way to implement a drop down list using webgrid?
#{
WebGrid gridBenefits = new WebGrid(Model.Benefits, rowsPerPage: 4);
}
<div class="row">
#gridBenefits.GetHtml(
tableStyle: "table table-responsive table-striped table-bordered",
columns: gridBenefits.Columns(
gridBenefits.Column(header: "Description", format: #<text><div class="edit" data-id="#item.BenefitID" data-identity="Benefits" data-propertyname="BenefitDescription"> #item.BenefitDescription</div></text>),
gridBenefits.Column(header: "Progress", format:#<text><div class="edit" data-id="#item.BenefitID" data-identity="Benefits" data-propertyname="Progress"> #item.ProgressID</div></text>)
)
)
</div>
My model is below for the progress drop down column:
public class Progress
{
public int ProgressID { get; set; }
public string Status { get; set; }
}
I would like to display 'Status' for each ProgressID in the drop down column. For the moment it displays the ProgressID currently, how can I adapt the code to have a drop down list instead?
I have not tested this, but my thoughts are something like this:
#{
WebGrid gridBenefits = new WebGrid(Model.Benefits, rowsPerPage: 4);
}
<div class="row">
#gridBenefits.GetHtml(
tableStyle: "table table-responsive table-striped table-bordered",
columns: gridBenefits.Columns(
gridBenefits.Column(header: "Description", format: #<text><div class="edit" data-id="#item.BenefitID" data-identity="Benefits" data-propertyname="BenefitDescription"> #item.BenefitDescription</div></text>),
gridBenefits.Column(header: "Progress", format: (item) => #Html.DropDownList("ProgressId", Model.First().Status.Select(l => new SelectListItem
{
Text = l.Text,
Value = l.Value,
Selected = ((WebGridRow)item)["ProgressId"].ToString() ==
l.Value
})))
)
)
</div>

How do I manipulate WebGrids?

I'm using ASP.NET and the MVC pattern.
I have the following code which I use to style the columns:
<div id="grid">
#grid.GetHtml(columns: grid.Columns(
grid.Column("Amount", "Amount", canSort: true, style: "column"),
grid.Column("ShelfLife", "ShelfLife", canSort: true, style: "column"),
grid.Column("Size", "Size", canSort: true, style: "column"),
grid.Column("Type", "Type", canSort: true, style: "column"),
grid.Column("Unit", "Unit", canSort: true, style: "column")
))
</div>
I use the following code to load the data for the grid:
#{
ViewBag.Title = "ListView";
Layout = "~/Views/Shared/_Layout.cshtml";
var grid = new WebGrid(Model, defaultSort: "null");
}
It's probably a long and trivial way of doing this... but I'd like to know how I can manipulate what's in the grid? For example, I'd like to add a button for every row. I'd also like to recolour every second row. How would I do this?
You can use styles for changing the color of rows in grid and check this link for manipulating the grid.
You can define custom css class in a separate css file
.comments {
width: 500px;
}
and then assign this class to the corresponding elements:
webGrid.Column(columnName: "TRP_Comments", header: "Comments", style: "comments")

MVC WebGrid Custom URL's For Sorting & Paging

I have been trying to fin a way to override the URL generated for sorting & paging. As i need to put a session ID in the URL that it generates. I have tried putting in custom formats. But that didn't work. It there an easier way?
#{
var grid = new WebGrid(canPage: true, canSort: true, ajaxUpdateContainerId: "grid", rowsPerPage: #Model.Paging.PageSize, defaultSort: "Test");
grid.Bind(Model.TestUnit, rowCount: Model.Paging.TotalRecordCount, autoSortAndPage: false, );
grid.Pager(WebGridPagerModes.FirstLast, firstText: "First", lastText: "Last");
#grid.GetHtml(htmlAttributes: new { id = "grid" }, tableStyle: "table table-striped table-hover",
columns: grid.Columns(
grid.Column("", format: #<img class="thumb" src="#" height="35" width="35" alt="" />),
grid.Column("Test", header: "Test"),
grid.Column("Test2", header: "Test2"),
grid.Column("", format: #<text>#Html.ActionLink("Details", "Details", new { id = item.test}) </text>, canSort: false)
));
}

MVC 5 Razor handling view when validation fails

I have an MVC Razor layout with a WebGrid.
#Html.ValidationSummary()
<div>
#model List<DelsDTO>
#{
var grid = new WebGrid(Model, defaultSort: "Name");
}
#grid.GetHtml(headerStyle: "webgrid-header", columns: grid.Columns(
grid.Column(header: "Select", format: #<text><input name="checkedDelUnits" type="checkbox" value="#item.delId" /></text>),
grid.Column("DelId", header: "ID"),
grid.Column("Name", style: "nameColLen"),
grid.Column("CRate", header: "C Rate", style: "span1", format: (item) =>
(item.CRate == null) ? String.Empty : String.Format("{0:0.00}", #item.CRate))
)
)
<td><input type="submit" name="saveChanges" value="Save Changes" /></td>
}
</div>
Using a submit button I perform validation checks in a controller method.
If the validation fails I set:
ModelState.AddModelError("", "No records Selected");
return View("Search");
At this point I have no datasource for the view so it is returned with an empty grid.
What is best practice for handling this?
Should I pass the webgrid datasource (model) from the view to the controller only to pass it back if validation fails? If so how do that?
If the validation fails you basically need to create the model once again since it is not saved anywhere. So if on the initial action you were doing something like (just an idea below):
var model = GetGridModel();
return View("Search", model);
You would need to do the same on submit when validation failed:
ModelState.AddModelError("", "No records Selected");
var model = GetGridModel();
return View("Search", model);

Saving all checkbox values from WebGrid in MVC 4

I am new to MVC 4. I am stuck in a situation and want some suggestions to resolve the problem. The problem scenario is:
I am rendering a WebGrid inside a partial view and the WebGrid format is as follows:
An IEnumerable collection is bound with the WebGrid. The view for binding WebGrid is:
#{
MIS.Areas.AdminModule.Models.AdminModuleViewModels.Module_UserGrp_Permission allPermissions = new MIS.Areas.AdminModule.Models.AdminModuleViewModels.Module_UserGrp_Permission();
}
#{
var grid = new WebGrid(Model, canPage: true, rowsPerPage: 10, selectionFieldName: "selectedRow", ajaxUpdateContainerId: "Title");
grid.Pager(WebGridPagerModes.NextPrevious);}
<div id="gridContent">
#grid.GetHtml(tableStyle: "webGrid",
headerStyle: "header",
alternatingRowStyle: "alt",
selectedRowStyle: "select",
columns: grid.Columns(
grid.Column(header: "Select",
format: #<input class="select" id="assignChkBx" name="assignChkBx" type="checkbox" #allPermissions.intMenuId/>),
grid.Column(header: "MenuId", format: (item) => item.intMenuId, style: "description"),
grid.Column(header: "Menu", format: (item) => item.strMenuName, style: "description", canSort: true),
grid.Column(header: "Add", format: #<text><input name="Add" type="checkbox" #(item.boolAddPer == true ? "Checked" : null) id="chkboxIsActiveAdd" /></text>),
grid.Column(header: "Edit", format: #<text><input name="Edit" type="checkbox" #(item.boolEditPer == true ? "Checked" : null) id="chkboxIsActiveEdit" /></text>),
grid.Column(header: "Delete", format: #<text><input name="Delete" type="checkbox" #(item.boolDeletePer == true ? "Checked" : null) id="chkboxIsActiveDelete" /></text>),
grid.Column(header: "Grant", format: #<text><input name="Grant" type="checkbox" #(item.boolGrantPer == true ? "Checked" : null) id="chkboxIsActiveGrant" /></text>)
))
</div>
And fetching data from database as follows (I am NOT using EntityFramework) :
var result = from column in dt.AsEnumerable()
select new Module_UserGrp_Permission
{
intMenuId = Convert.ToInt32(column["MenuId"]),
intUserGrpId = Convert.ToInt32(column["UserGrpId"]),
strMenuName = Convert.ToString(column["MenuName"]),
boolAddPer = Convert.ToBoolean(column["boolGAdd"]),
boolEditPer = Convert.ToBoolean(column["boolGEdit"]),
boolDeletePer = Convert.ToBoolean(column["boolGDel"]),
boolViewPer = Convert.ToBoolean(column["boolGView"]),
boolGrantPer = Convert.ToBoolean(column["boolGGrant"])
};
return new List<MIS.Areas.AdminModule.Models.AdminModuleViewModels.Module_UserGrp_Permission>(result);
Now the problem is I have to save all the checked/unchecked items from this WebGrid.
What should I do to save all the values after clicking the 'Save' button.
Please suggest possible solutions.
Thank you all.
Since all of your check boxes have the same name you can do a
string result = Request.Form["assignChkBx"].ToString();
on your controller which will give you a list of all of the checked checkboxes. Hopefully this helps.
While it's not a coded worked solution, I've managed to get this working with a single checkbox. Should be simple enough to get it wired up for multiple: ASP.NET MVC Display an HTML Table with Checkboxes to Select Row Items

Categories