ASP.Net MVC facing difficulties to pass editable tabular data to action - asp.net-mvc

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; }
}

Related

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).

How to add View/Create function in MVC and update it into index?

I'm still new to MVC but really curious about it. I have my create view function, but I was wondring why Im not be able to show new data that I create back to my index?
here is my controller:
//GET /UserActivity/Create
public ActionResult Create()
{
UserActivityModels ua = new UserActivityModels();
return View(userActivity);
}
//
// POST: /UserActivity/Create
[HttpPost]
public ActionResult Create(FormCollection formCollection)
{
try
{
UserActivityModels ua = new UserActivityModels();
ua.Id = Int32.Parse(formCollection["Id"]);
ua.CreatedBy = Int32.Parse(formCollection["CreatedBy"]);
ua.CreatedOn = DateTime.Parse(formCollection["CreatedOn"]);
ua.ModifiedBy = Int32.Parse(formCollection["ModifiedBy"]);
ua.ModifiedOn = DateTime.Parse(formCollection["ModifiedOn"]);
ua.ContactId = formCollection["ContactId"];
ua.StatusCode = Int32.Parse(formCollection["StatusCode"]);
ua.StateCode = Int32.Parse(formCollection["StateCode"]);
ua.EntityName = formCollection["EntityName"];
ua.EntityId = Int32.Parse(formCollection["EntityId"]);
ua.ActivityType = Int32.Parse(formCollection["ActivityType"]);
ua.ActivityStatus = formCollection["ActivityStatus"];
ua.DueDate = DateTime.Parse(formCollection["DueDate"]);
ua.ActualEndDate = DateTime.Parse(formCollection["ActualEndDate"]);
ua.MasqueradeOn = DateTime.Parse(formCollection["MasqueradeOn"]);
ua.MasqueradeBy = Int32.Parse(formCollection["MasqueradeBy"]);
return RedirectToAction("Index");
}
catch
{
return View("Index");
}
}
the model:
public class UserActivityModels
{
public int Id { get; set; }
public DateTime CreatedOn { get; set; }
public int CreatedBy { get; set; }
public int ModifiedBy { get; set; }
public DateTime ModifiedOn { get; set; }
public string ContactId { get; set; }
public string EntityName { get; set; }
public int EntityId { get; set; }
public int StatusCode { get; set; }
public int StateCode { get; set; }
public int ActivityType { get; set; }
public string ActivityStatus { get; set; }
public DateTime DueDate { get; set; }
public DateTime ActualEndDate { get; set; }
public DateTime MasqueradeOn { get; set; }
public int MasqueradeBy { get; set; }
public string ContactName { get; set; }
//public int TotalCount { get; set; }
// public List<string> userActivity { get; set; }
}
Does anyone could tell me why when I click "submit" button, the new created data is now showing in the index? Thanks
and Here is the View/Index:
#{
ViewBag.Title = "Index";
Layout = "~/Views/Shared/_LayoutMain.cshtml";
}
<h2>Index</h2>
#*<p>
#Html.ActionLink("Create New", "Create")
</p>*#
<h3>User Activity</h3>
#using (Html.BeginForm("index", null, FormMethod.Get))
{
<div class="row">
<div class="col-sm-8">
<div class="input-group">
<input type="text"
name="filter"
value="#ViewBag.filter"
class="form-control"
style="display: inline"
placeholder="Search by Contact Name or Entity Name" />
<span class="input-group-btn">
<button class="btn btn-default" type="submit">Go</button>
</span>
</div>
</div>
<div class="pull-right col-lg-1">
<a class="btn btn-success" data-modal="" href="/UserActivity/Create" id="btnCreate">
<span class="glyphicon glyphicon-plus"></span>
</a>
</div>
</div>
<div class="table-responsive" style="margin-top:5px;">
#{
var grid = new WebGrid(
Model,
canPage: true,
rowsPerPage: 5,
canSort: true);
//ajaxUpdateContainerId: "grid");
//grid.Bind(Model, rowCount: (int)ViewData["totalCount"], autoSortAndPage: false);
grid.Pager(WebGridPagerModes.All);
#grid.GetHtml(
htmlAttributes: new { id = "grid" },
// id for ajaxUpdateContainerId parameter
fillEmptyRows: false,
tableStyle: "table table-striped",
mode: WebGridPagerModes.All,
columns: grid.Columns(
//grid.Column("Id", "Id"),
grid.Column("Id", "Id", style: "col-lg-1", canSort: true),
grid.Column("CreatedBy", "CreatedBy", style: "col-lg-6"),
grid.Column("CreatedOn", header: "CreatedOn", style: "col-lg-2", canSort: true),
grid.Column("ModifiedBy", header: "ModifiedBy", style: "col-lg-2"),
grid.Column("ModifiedOn", header: "ModifiedOn", style: "col-lg-2"),
grid.Column("ContactId", header: "ContactId", style: "col-lg-2"),
grid.Column("EntityName", header: "EntityName", style: "col-lg-2"),
//grid.Column("EntityName", "EntityName", style: "col-lg-1", canSort: true),
grid.Column("EntityId", header: "EntityId", style: "col-lg-2"),
grid.Column("StatusCode", header: "StatusCode", style: "col-lg-2"),
grid.Column("StateCode", header: "StateCode", style: "col-lg-2"),
grid.Column("ActivityType", header: "ActivityType", style: "col-lg-2"),
grid.Column("ActivityStatus", header: "ActivityStatus", style: "col-lg-2"),
grid.Column("DueDate", header: "DueDate", style: "col-lg-2"),
grid.Column("ActualEndDate", header: "ActualEndDate", style: "col-lg-2"),
grid.Column("MasqueradeOn", header: "MasqueradeOn", style: "col-lg-2"),
grid.Column("MasqueradeBy", header: "MasqueradeBy", style: "col-lg-2"),
grid.Column("ContactName", header: "ContactName", style: "col-lg-2"),
//grid.Column("ContactName", "ContactName", style: "col-lg-1", canSort: true),
grid.Column(header: "Action", canSort: false, style: "action",
format: #<text>
#Html.Raw("<a data-modal='' href='/UserActivity/Details/" + item.Id + "' id='" + item.Id + "' title='Detail'> <span class='glyphicon glyphicon-search'> </span> </a>")
#Html.Raw("<a data-modal='' href='/UserActivity/Edit/" + item.Id + "' id='" + item.Id + "' title='Edit'> <span class='glyphicon glyphicon-edit'> </span> </a>")
#Html.Raw("<a data-modal='' href='/UserActivity/Delete/" + item.Id + "' id='" + item.Id + "' title='Delete'> <span class='glyphicon glyphicon-trash'> </span> </a>")
</text>)
));
}
</div>
}
Inside your Index method, you would have to retrieve the model you created in the Create method, and use that as an argument when returning the view.
One way to pass a model from one controller method to another is to use the TempData dictionary.
So what you can do is this: In your Create method, just before calling return RedirectToAction("Index");, store your model in TempData:
TempData["MyModel"] = ua;
Then, in the Index method, retrieve the model from TempData and pass it into the view:
var myModel = (UserActivityModels)TempData["MyModel"];
return View(myModel);

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>

post items of webgrid asp.net mvc3

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...

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);
}

Resources