post items of webgrid asp.net mvc3 - asp.net-mvc

I have these DTO's
public class Header
{
public int HeaderId{get;set;}
public int Description{get;set;}
public List<HeaderItem> HeaderItems{get;set;}
}
public class HeaderItem
{
public int HeaderItemId{get;set;}
public string DetailDescription{ get; set; }
public bool Selected{ get; set; }
}
and I have this Controller
[HttpPost]
public ActionResult PostMethod(Header dto)
{
...
}
and this html
#using (Html.BeginForm("PostMethod", "Controller", FormMethod.Post, new { id = "form" }))
{
#Html.TextBoxFor(x => x.Description)
var grid = new WebGrid(Model.HeaderItems);
}
#grid.GetHtml(tableStyle: "grid",
htmlAttributes: new { id = "grid" },
columns: grid.Columns(
grid.Column("Selected", "Seç", format: (item) => Html.CheckBox(String.Format("Selected_{0}", (int)item.HeaderItemId), false)),
grid.Column("HeaderItemId", "", format: (item) => Html.Hidden("HeaderItemId")),
grid.Column("DetailDescription", "Description")
)
}
So, this grid have a checkbox and a HiddenField that hold the HeaderItemId value of each row.
I would like to post my form and have my property HeaderItems of Header class filled.
How could I reach this solution?

How could I reach this solution?
Like this:
columns: grid.Columns(
grid.Column(
"Selected",
"Seç",
format:
#<text>
#{ var index = Guid.NewGuid().ToString(); }
#Html.Hidden("HeaderItems.Index", index)
#Html.Hidden("HeaderItems[" + index + "].HeaderItemId", (int)item.HeaderItemId)
#Html.CheckBox("HeaderItems[" + index + "].Selected", (bool)item.Selected)
</text>
),
grid.Column("HeaderItemId")
grid.Column("DetailDescription", "Description")
)

Try change your Html.CheckBox for Html.CheckBoxFor and the same for Html.Hidden for Html.HiddenFor.
It would be:
#grid.GetHtml(tableStyle: "grid",
htmlAttributes: new { id = "grid" },
columns: grid.Columns(
grid.Column("Selected", "Seç", format: (item) => Html.CheckBoxFor(m => item.HeaderItemId)),
grid.Column("HeaderItemId", "", format: (item) => Html.Hidden(m => item.HeaderItemId)),
grid.Column("DetailDescription", "Description")
)
)
I have not tested it thought...

Related

ASP.Net MVC facing difficulties to pass editable tabular data to action

i am working with webgrid to show data in tabular format in edit mode. when my application is running then textboxes appear in tabular format with data. when user change existing data in textbox and submit button clicked then my server side action is getting called but no data is passing there which causes my List<UserModel> oUserModel is always null
here i am pasting my view and action code.
view code
#model List<MVCCRUDPageList.Controllers.UserModel>
#using (Html.BeginForm(null,null,FormMethod.Post))
{
var grid = new WebGrid(Model);
var rowNum = 0;
<div id="gridContent" style=" padding:20px; ">
#grid.GetHtml(
tableStyle: "table",
alternatingRowStyle: "alternate",
selectedRowStyle: "selected",
headerStyle: "header",
columns: grid.Columns
(
//grid.Column("RowNumber", style: "HideFirstCol", format: item => rowNum = rowNum + 1),
grid.Column(null, null, format: #<input type="hidden" name="IDHidden" value="rowNum + 1" />),
grid.Column("First Name",
style: "col2",
format: #<text>
#Html.TextBox("UserModel[" + (rowNum - 1).ToString() + "].FirstName", (object)item.FirstName)
</text>),
grid.Column("Last Name",
style: "col2",
format: #<text>
#Html.TextBox("UserModel[" + (rowNum - 1).ToString() + "].LastName", (object)item.LastName)
</text>)
))
</div>
<input type="submit" name="SaveButton" value="Save" />
}
Action code
public class WebGridEditableController : Controller
{
// GET: WebGridEditable
public ActionResult Index()
{
List<UserModel> users = UserModel.getUsers();
return View(users);
}
// GET: WebGridEditable
[HttpPost]
public ActionResult Index(List<UserModel> oUserModel)
{
return View(oUserModel);
}
}
public class UserModel
{
public int ID { get; set; }
public string FirstName { get; set; }
public string LastName { get; set; }
public static List<UserModel> getUsers()
{
List<UserModel> users = new List<UserModel>()
{
new UserModel (){ ID=1, FirstName="Anubhav", LastName="Chaudhary" },
new UserModel (){ ID=2, FirstName="Mohit", LastName="Singh" },
new UserModel (){ ID=3, FirstName="Sonu", LastName="Garg" },
new UserModel (){ ID=4, FirstName="Shalini", LastName="Goel" },
new UserModel (){ ID=5, FirstName="James", LastName="Bond" },
};
return users;
}
}
please highlight what mistake i have made there which preventing tabular data to pass to server side action.
screen shot
thanks
problem lies here grid.Column(null, null, format: #<input type="hidden" name="IDHidden" value="rowNum + 1" />),
now it is solved. full code
#model MVCCRUDPageList.Controllers.UserVM
#using (Html.BeginForm("Index", "WebGridEditable", FormMethod.Post))
{
var grid = new WebGrid(Model.UserList, canSort: false, canPage: false);
var rowNum = 0;
<div id="gridContent" style=" padding:20px; ">
#grid.GetHtml(
tableStyle: "table",
alternatingRowStyle: "alternate",
selectedRowStyle: "selected",
headerStyle: "header",
columns: grid.Columns
(
#*grid.Column(null, null, format: #<input type="hidden" name="IDHidden" value="rowNum + 1" />),*#
grid.Column(null, null, format: item => rowNum = rowNum + 1),
grid.Column("First Name",
style: "col2",
format: (item) => #Html.TextBox("UserList[" + (rowNum - 1).ToString() + "].FirstName", (object)item.FirstName)
),
grid.Column("Last Name",
style: "col2",
format: (item) =>
#Html.TextBox("UserList[" + (rowNum - 1).ToString() + "].LastName", (object)item.LastName)
)
))
</div>
<input type="submit" name="SaveButton" value="Save" />
}
controller and action code
public class WebGridEditableController : Controller
{
// GET: WebGridEditable
public ActionResult Index()
{
var usermodel = new UserVM
{
UserList = new List<UserModel>
{
new UserModel (){ ID=1, FirstName="Anubhav", LastName="Chaudhary" },
new UserModel (){ ID=2, FirstName="Mohit", LastName="Singh" },
new UserModel (){ ID=3, FirstName="Sonu", LastName="Garg" },
new UserModel (){ ID=4, FirstName="Shalini", LastName="Goel" },
new UserModel (){ ID=5, FirstName="James", LastName="Bond" }
}
};
return View(usermodel);
}
// GET: WebGridEditable
[HttpPost]
public ActionResult Index(UserVM oUserVM)
{
return View(oUserVM);
}
}
public class UserVM
{
public List<UserModel> UserList { get; set; }
}
public class UserModel
{
public int ID { get; set; }
public string FirstName { get; set; }
public string LastName { get; set; }
}
The same done with textboxfor using webgrid
razor view code
#model List<MVCCRUDPageList.test.Controllers.Student>
#{
ViewBag.Title = "Index";
}
<h2>Index</h2>
#using (Html.BeginForm("Index", "WebGrid", FormMethod.Post))
{
var grid = new WebGrid(Model, canSort: false, canPage: false);
var rowNum = 0;
<div id="gridContent" style=" padding:20px; ">
#grid.GetHtml(
tableStyle: "table",
alternatingRowStyle: "alternate",
selectedRowStyle: "selected",
headerStyle: "header",
columns: grid.Columns
(
grid.Column(null, null, format: item => rowNum = rowNum + 1),
grid.Column("First Name", format: (item) => #Html.TextBoxFor(m => m[rowNum - 1].FirstName, new { #class = "edit-mode" })),
grid.Column("Last Name", format: (item) => #Html.TextBoxFor(m => m[rowNum - 1].LastName, new { #class = "edit-mode" }))
))
<input type="submit" value="Submit" />
</div>
}
Controller and action code
public class WebGridController : Controller
{
// GET: WebGrid
public ActionResult Index()
{
var UserList = new List<Student>
{
new Student (){ ID=1, FirstName="Anubhav", LastName="Chaudhary" },
new Student (){ ID=2, FirstName="Mohit", LastName="Singh" },
new Student (){ ID=3, FirstName="Sonu", LastName="Garg" },
new Student (){ ID=4, FirstName="Shalini", LastName="Goel" },
new Student (){ ID=5, FirstName="James", LastName="Bond" }
};
return View(UserList);
}
[HttpPost]
public ActionResult Index(List<Student> oStudent)
{
return View(oStudent);
}
}
public class Student
{
public int ID { get; set; }
public string FirstName { get; set; }
public string LastName { get; set; }
}

ASP.Net MVC: Selected country id value in dropdown not passing to controller

i have webgrid where i am showing student data like ID, name and student country. all data is in editable format. country data appear in dropdown.
my UI
here is my controller code
public class WebGridMoreControlsController : Controller
{
// GET: WebGridMoreControls
public ActionResult Index()
{
StudentListViewModel osvm = new StudentListViewModel();
return View(osvm);
}
[HttpPost]
public ActionResult Index(StudentListViewModel oStudentListViewModel)
{
return View(oStudentListViewModel);
}
}
here is my model code
public class Student
{
public int ID { get; set; }
public string Name { get; set; }
public int CountryID { get; set; }
}
public class Country
{
public int ID { get; set; }
public string Name { get; set; }
}
viewmodel code
public class StudentListViewModel
{
public IList<Student> Students { get; set; }
public int SelectedCountryId { set; get; }
public List<Country> Country { get; set; }
public StudentListViewModel()
{
Students = new List<Student>
{
new Student{ID=1,Name="Keith",CountryID=1},
new Student{ID=2,Name="Paul",CountryID=2},
new Student{ID=3,Name="Sam",CountryID=3}
};
Country = new List<Country>
{
new Country{ID=1,Name="India"},
new Country{ID=2,Name="UK"},
new Country{ID=3,Name="USA"}
};
}
}
here is my razor view code
#model MVCCRUDPageList.Models.StudentListViewModel
#{
ViewBag.Title = "Index";
}
<h2>Student View Model</h2>
#using (Html.BeginForm("Index", "WebGridMoreControls", FormMethod.Post))
{
var grid = new WebGrid(Model.Students, canSort: false, canPage: false);
var rowNum = 0;
<div id="gridContent" style=" padding:20px; ">
#grid.GetHtml(
tableStyle: "table",
alternatingRowStyle: "alternate",
selectedRowStyle: "selected",
headerStyle: "header",
columns: grid.Columns
(
grid.Column(null, null, format: item => rowNum = rowNum + 1),
grid.Column("ID", format: (item) => #Html.TextBoxFor(m => m.Students[rowNum - 1].ID, new { #class = "edit-mode" })),
grid.Column("Name", format: (item) => #Html.TextBoxFor(m => m.Students[rowNum - 1].Name, new { #class = "edit-mode" })),
grid.Column("Country", format: (item) =>
#Html.DropDownListFor(x => x.SelectedCountryId,
new SelectList(Model.Country, "ID", "Name", Model.SelectedCountryId = item.CountryID),
"-- Select States--", new { id = "cboCountry", #class = "edit-mode" }))
))
<input type="submit" value="Submit" />
</div>
}
where did i made the mistake for which changed country ID from drowdown not getting pass to action when i submit form. country id is also 0.
Your Student model contains a property CountryID which is the property you need to bind to. Remove the public int SelectedCountryId { set; get; } property from your view model, and change the code in the view to bind to CountryID
grid.Column("Country", format: (item) =>
#Html.DropDownListFor(
x => x.Students[rowNum - 1].CountryID,
new SelectList(Model.Country, "ID", "Name", item.CountryID),
"-- Select States--",
new { #class = "edit-mode" }
)
)
In addition, remove the new { id = "cboCountry" } from the DropDownListFor() method which is generating invalid html (duplicate id attributes)
Note you current code binds the value of the selected option in each <select> to your SelectedCountryId property, but the DefaultModelBinder only binds the first value in the request, so the value of SelectedCountryId would be the value of the selected option in the first row (i.e. the ID associated with 'India' in your image).

Filtering a WebGrid with a DropDownList in MVC4

I am using a WebGrid, which i bind to a List of objects containing information about deliveries. I want to be able to filter said WebGrid using a DropDownList containing Customers. When I select a Customer in the DropDownList the change-method sends an Ajax call which is supposed to get the new items for the WebGrid.
The call is successful, but nothing happens. The WebGrid doesn't change at all. I even tried sending an Ajax call identical to the ones sent when sorting the list. But nothing happens.
What am I doing wrong here?
ViewModel:
public class DeliveriesViewModel : PageViewModel<DeliveriesPage>
{
public DeliveriesViewModel(DeliveriesPage currentPage) : base(currentPage)
{
DeliveryItems = new List<DeliveryItem>();
}
public List<DeliveryItem> DeliveryItems { get; set; }
public List<SelectListItem> Customers { get; set; }
}
Controller:
public ActionResult Index(DeliveriesPage currentPage, string customer)
{
var model = new DeliveriesViewModel(currentPage);
model.Customers = _deliveryService.GetCustomers();
model.DeliveryItems = customer == null ? _deliveryService.GetDeliveryItems() : _deliveryService.GetDeliveryItems(customer);
return View(model);
}
View:
#model DeliveriesViewModel
<h1>#Model.CurrentPage.PageName</h1>
#Html.DropDownList("customerDropDown", Model.Customers)
#Html.Partial("_grid", Model)
<script type="text/javascript">
$("#customerDropDown").change(function () {
$.get("?Customer="+$("#customerDropDown").val());
});
</script>
_grid partial View:
#model DeliveriesViewModel
#{
var grid = new WebGrid(Model.DeliveryItems, canPage:true, canSort: true, ajaxUpdateContainerId:"container-grid");
}
<div id="container-grid">
#grid.GetHtml(
columns: grid.Columns(
grid.Column("DeliveryId"),
grid.Column("CustomerName"),
grid.Column("ShipNumber"),
grid.Column("ShipName"),
grid.Column("Product"),
grid.Column("PlannedWeight"),
grid.Column("TotalWeight"),
grid.Column("ShipStatus"),
grid.Column("TransportTo"),
grid.Column("TransportFrom"),
grid.Column("RevDate"),
grid.Column("ShipStemDept"),
grid.Column("ShipRealDept"),
grid.Column("ShipStemArr"),
grid.Column("ShipRealArr"),
grid.Column("TranspMonth"),
grid.Column("TranspYear")
))
</div>
$.get("?Customer="+$("#customerDropDown").val()); sends an AJAX call to the server and that's about it. You haven't subscribed to the success callback in order to update your DOM. So it is not surprising that nothing happens.
So try like this:
<script type="text/javascript">
$('#customerDropDown').change(function () {
var url = '#Url.Action("index")';
$.get(url, { customer: $(this).val() }, function(result) {
$('#container-grid').html(result);
});
});
</script>
Notice how I have used the UrlHelper to calculate the correct url to your controller action, I have then passed the selected value of the dropdown as second parameter to the $.get method and last but not least I have subscribed to the success callback of the ajax request and updated the #container-grid div with the results returned by the controller action.
Also since you are calling this action with AJAX, you should return only a PartialView from it and not an entire View. This partial view should contain your grid. Otherwise you will end up with duplicate layout injected into the div.
Model
public class EmployerTestResultsModel
{
[Display(Name = "Employer List")]
public IEnumerable<SelectListItem> EmployerList { get; set; }
[Required]
public string SelectedEmployerId { get; set; }
public List<EmployerTestResultsModel> EmployerGrid { get; set; }
public Int64 FileId { get; set; }
[Display(Name = "File Name")]
public string FileName { get; set; }
[DataType(DataType.Date)]
public DateTime Date { get; set; }
[Display(Name = "Scheme Id")]
public string SchemeId { get; set; }
public string Status { get; set; }
[Display(Name = "Validation Error Report")]
public string ValidationErrorReport { get; set; }
}
controller
[HttpGet]
public ActionResult EmployerTestResults()
{
EmployerTestResultsModel model = new EmployerTestResultsModel();
ViewBag.HideSection = true;
model.EmployerList = (from d in _context.Employers
select new System.Web.Mvc.SelectListItem
{
Text = d.EmployerName,
Value = d.EmployerId
});
model.EmployerGrid = (from efd in _context.EmployerFileDatas
// join efhd in _context.EmployerFileHeaderDetails on efd.FileDataIdentityKey equals efhd.FileDataIdentityKey
orderby efd.EmployerId , efd.Timestamp
select new EmployerTestResultsModel
{
FileId = efd.FileDataIdentityKey,
FileName = efd.FileName,
Date = efd.Timestamp,
//SchemeId = efhd.SchemeId,
Status = efd.ValidationStatus,
ValidationErrorReport = "View"
}).ToList();
return View("EmployerTestResults", model);
}
View:
#model EFITestHarness.Models.EmployerTestResultsModel
#using System.Web.Helpers;
#{
ViewBag.Title = "EmployerTestResults";
Layout = "~/Views/Shared/_Layout.cshtml";
}
<script src="~/Scripts/jquery-1.7.1.js"></script>
<script src="~/Scripts/jquery.unobtrusive-ajax.js"></script>
#using (Html.BeginForm("EmployerTestResults", "Home", FormMethod.Post, new { #class = "form-horizontal" }))
{
<div class="text-danger" style="font-size:large;">
#Html.ValidationSummary(true)
</div>
<div class="form-group ">
#Html.LabelFor(s => s.EmployerList, null, new { #class = "col-md-2 control-label" })
<div class="col-md-3">
#Html.DropDownListFor(s => s.SelectedEmployerId, Model.EmployerList, "----All----", new { style = "width:250px", id = "ddl", #class = "dropdown1" })
#Html.ValidationMessageFor(s => s.EmployerList, null, new { #class = "text-danger" })
</div>
</div>
<div id="EmployeeViewGrid">
#Html.Partial("~/Views/EmployerView.cshtml", Model.EmployerGrid)
</div>
}
<script type="text/javascript">
$('#ddl').change(function (e) {
var employer = $('#ddl').val();
$.get('#Url.Action("Filter")', { id: employer }, function (result) {
$('#EmployeeViewGrid').html(result);
});
e.preventDefault();
});
</script>
Controller:
[HttpGet]
public ActionResult Filter(string id)
{
EmployerTestResultsModel model = new EmployerTestResultsModel();
List<EmployerTestResultsModel> objEmployerDetails = new List<EmployerTestResultsModel>();
objEmployerDetails = _repository.getEmployerDetails(id);
model.EmployerGrid = objEmployerDetails;
return PartialView("~/Views/EmployerView.cshtml", model.EmployerGrid);
}
partial View:
#model IEnumerable<EFITestHarness.Models.EmployerTestResultsModel>
#using System.Web.Helpers;
#{
ViewBag.Title = "EmployerTestResultsModel";
//Layout = "~/Views/Shared/_Layout.cshtml";
}
<script src="~/Scripts/jquery-1.7.1.js"></script>
<div id="gridposition" style="overflow: scroll; height: 300px; overflow-x: hidden;">
#{
var grid = new WebGrid(Model, canPage: true, rowsPerPage: 5, selectionFieldName: "selectedRow", ajaxUpdateContainerId: "gridposition"); grid.Pager(WebGridPagerModes.NextPrevious);
#grid.GetHtml(tableStyle: "webGrid",
footerStyle: "foot",
headerStyle: "webGridHeader",
alternatingRowStyle: "webGridAlt",
htmlAttributes: new { id = "positionGrid" },
selectedRowStyle: "select",
fillEmptyRows: true,
columns: grid.Columns(
grid.Column("FileName"), //the model fields to display
grid.Column("Date"),
grid.Column("SchemeId"),
grid.Column("Status"),
grid.Column("ValidationErrorReport", format: (item => Html.ActionLink((string)(#item.ValidationErrorReport).ToString(), "EmployerValidationResults", new { FileId = #item.FileId, #style = "color:blue;" })))
))
}
</div>

Object reference not set to an instance of an object for dropdownlist in model

I have no idea why this is happening, I have set the values and debugged it, but it is just not passing the information from the controller to the view. Here is what is going on
Model:
public class QueueFilterModel
{
public string SelectedFilter { get; set; }
public string query { get; set; }
public List<string> MyFilterList { get; set; }
}
Controller:
[HttpGet]
public ActionResult Queue()
{
QueueFilterModel model = new QueueFilterModel()
{
SelectedFilter = "All",
query = "SELECT * FROM [CHAVI].[dbo].[TicketQueue]",
MyFilterList = new List<string>()
};
model.MyFilterList.Add("All");
model.MyFilterList.Add("Open");
model.MyFilterList.Add("Closed");
return View();
}
View:
#model RazorARPP.Models.QueueFilterModel
#{
ViewBag.Title = "Queue";
}
<h2>Queue</h2>
<form action="" method="post" enctype="multipart/form-data" id="MyForm">
Filter
<div>
Filter Options:
</div>
<div>
#Html.DropDownList("test", new SelectList(Model.MyFilterList,Model.SelectedFilter))
</div>
<h3>Insert Instructions Here</h3>
#{
var DB = Database.Open("CHAVI");
var grid = new WebGrid(DB.Query("SELECT * FROM [TicketQueue]"), null, null, 20);
#grid.GetHtml(
tableStyle: "webgrid",
columns: grid.Columns(
grid.Column(header: "Link", style: "labelcolumn", format: (item) => Html.ActionLink("Edit Item", "EditQueue", new { id = item.QueueID})),
grid.Column("Description", "Description"),
grid.Column("QueueDate", "QueueDate"),
grid.Column("Note", "Note"),
grid.Column("Status", "Status"),
grid.Column("LastUpdated", "LastUpdated")
)
)
}
</form>
The grid part is working fine (and the query). The problem is in the dropdown, it isn't set to anything there. Any thoughts? Thanks.
Are you not passing the model to view?
Should it not be
public ActionResult Queue()
{
QueueFilterModel model = new QueueFilterModel()
{
SelectedFilter = "All",
query = "SELECT * FROM [CHAVI].[dbo].[TicketQueue]",
MyFilterList = new List<string>()
};
model.MyFilterList.Add("All");
model.MyFilterList.Add("Open");
model.MyFilterList.Add("Closed");
return View(model);
}
Try using:-
public ActionResult Queue()
{
QueueFilterModel model = new QueueFilterModel()
{
SelectedFilter = "All",
query = "SELECT * FROM [CHAVI].[dbo].[TicketQueue]",
MyFilterList = new List<string>()
};
model.MyFilterList.Add("All");
model.MyFilterList.Add("Open");
model.MyFilterList.Add("Closed");
return View(model);
}

Change value of grid item

I have table:
#using (Html.BeginForm()) {
#Html.ValidationSummary(true)
<fieldset>
<legend>Add</legend>
<br />
#{
var grid = new WebGrid(ViewBag.produkty,null, "names", 5);
}
#grid.GetHtml(
tableStyle: "grid",
headerStyle: "head",
alternatingRowStyle: "alt",
columns: grid.Columns(
grid.Column("name"),
grid.Column("value"),
grid.Column(header: "Add", format: (item) =>
new HtmlString(
Html.TextBoxFor(model => model.add).ToString())),
grid.Column( header: "Ok", format: (item) =>
new HtmlString(
Html.ActionLink("OK", "add_method", new { ID_name = item.ID_name }).ToString()))
)
)
</fieldset>
}
Controller:
public ActionResult use()
{
var nam = (from d in baza.Names
select new { d.ID_name, d.name, d.value}).ToList();
ViewBag.names= nam;
return View();
}
public ActionResult add_method(int ID_name, useModel use)
{
Use us = new Use();
var dat = DateTime.Today;
us.value = use.add;
us.ID_Name= ID_name;
us.data = dat;
baza.Zuzycies.InsertOnSubmit(us);
baza.SubmitChanges();
return RedirectToAction("use", "Product");
}
Model:
public class useModel
{
public int ID_name{ get; set; }
public decimal value{get;set;}
public string date { get; set; }
}
So, I have list of product on page. And I want to add a value (amount of product) into TextBox and press a ActionLink "OK" next to the textbox. How can I get amount of product in add_method? Or how insert submit button next to every one product (instead ActionLink "OK"), then is enought make use POST method...
You can use a grid componet with built-in edits functions (like the telerik Grid).
I think it's better to use ajax not reagular post request for your scenario.
Or you can do that ajax calls to the server with jquery, just send the parameters to the controller.

Resources