Change value of grid item - asp.net-mvc

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.

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 use linq for showing image in webgrid [duplicate]

in web-grid i can not use navigation properties between my classes(products and productimages classes). for example i have used below code in web grid:
grid.Column("", "test",item=> (item.ProductImages.First().Id)+(item.Price))
but i got error:
'System.Collections.Generic.HashSet<WebStore.Models.ProductImage>' does not contain a definition for 'First'
my total code is like below:
#model IEnumerable<WebStore.Models.Product>
#using System.Linq;
#{
var grid = new WebGrid(source: Model, rowsPerPage: 5,ajaxUpdateContainerId:"divGrid");
}
#grid.GetHtml(tableStyle: "gridStyle", headerStyle: "gridHeader", rowStyle: "gridRow", alternatingRowStyle: null,htmlAttributes:new{Id="divGrid"},
columns: new WebGridColumn[] {
grid.Column("ProductName", "Product Name"),
grid.Column("Price", "Price"),
grid.Column("Description", "Description"),
grid.Column("CategoryName","Category Name",x=>x.Category.CategoryName),
grid.Column("", "test",item=> (item.ProductImages.First().Id)+(item.Price)),
grid.Column("","",x=>Html.ActionLink("Edit", "Edit", new{id=x.Id})),
grid.Column("","",x=>Html.ActionLink("Details", "Details", new{id=x.Id})),
grid.Column("","",x=>Html.ActionLink("Delete", "Delete", new{id=x.Id}))
}
)
this is my index view:
#model IEnumerable<WebStore.Models.Product>
#using System.Linq
#{
ViewBag.Title = "Index";
Layout = "~/Views/Shared/_LayoutCategory.cshtml";
}
<br/>
<p>
#Html.ActionLink("Create New", "Create")
</p>
<div id="divGrid">
#{ Html.RenderPartial("_ProductTitle", Model); }
</div>
this is my RenderPartial that use web grid before i posted:
#model IEnumerable<WebStore.Models.Product>
#using System.Linq
#ViewBag.test
#{
var grid = new WebGrid(source: Model, rowsPerPage: 5,ajaxUpdateContainerId:"divGrid");
}
#grid.GetHtml(tableStyle: "gridStyle", headerStyle: "gridHeader", rowStyle: "gridRow", alternatingRowStyle: null,htmlAttributes:new{Id="divGrid"},
columns: new WebGridColumn[] {
grid.Column("ProductName", "Product Name"),
grid.Column("Price", "Price"),
grid.Column("Description", "Description"),
grid.Column("CategoryName","Category Name",x=>x.Category.CategoryName),
grid.Column("", "test",item=>(int) (item.ProductImages.FirstOrDefault().Id)+(int)(item.Price)),
grid.Column("","",x=>Html.ActionLink("Edit", "Edit", new{id=x.Id})),
grid.Column("","",x=>Html.ActionLink("Details", "Details", new{id=x.Id})),
grid.Column("","",x=>Html.ActionLink("Delete", "Delete", new{id=x.Id}))
}
)
It's because definition of First is available in System.Linq. So, you should have System.Linq in your razor page :
#using System.Linq;
if you are using Linq in multiple page, you can add System.Linq namespace in web.config so that you do not need to write above using in each page. You can add namespace in web.config in following configuration :
<system.web.webPages.razor>
<pages>
<namespaces>
<add namespace="System.Linq" />
</namespaces>
</pages>
</system.web.webPages.razor>
i got the answer of my question with below code from the net:
I followed your steps and test your code and the same error display. So I think the format in your code can not be used in webgrid. So I think about another way to meet your requirement: we need a ViewModel to display what you want to show in the View and search the first item in Controller then save as ViewModel and pass the ViewModel to View, then we do not need search in the View. Here I will show you the steps with my demo.
Now, we have two model Product and Quantity that one product has many quantities. We should create a ViewModel.
ViewModel.cs:
public class ViewModel
{
public string Id { get; set; }
public string Name { get; set; }
public string Description { get; set; }
public long quan { get; set; }
}
We can initialize some data and search the first value of Quantity depend on Product in Controller and assign to the ViewModel.
InventoryController .cs:
public class InventoryController : Controller
public ActionResult WebgridSample()
{
ObservableCollection<Product> inventoryList =
new ObservableCollection<Product>();
inventoryList.Add(new Product
{
Id = "P101",
Name = "Computer",
Description = "All type of computers",
quantity = new List<Quantity>
{
new Quantity {QUAN = 100 },
new Quantity {QUAN = 200 },
new Quantity {QUAN = 300 }
}
});
inventoryList.Add(new Product
{
Id = "P102",
Name = "Laptop",
Description = "All models of Laptops",
quantity = new List<Quantity>
{
new Quantity {QUAN = 400 },
new Quantity {QUAN = 500 },
new Quantity {QUAN = 600 }
},
});
inventoryList.Add(new Product
{
Id = "P103",
Name = "Camera",
Description = "Hd cameras",
quantity = new List<Quantity>
{
new Quantity {QUAN = 700 },
new Quantity {QUAN = 800 },
new Quantity {QUAN = 900 }
}
});
IEnumerable<string> model = (from sig in inventoryList
select new ViewModel
{
Name = sig.Name,
Description = sig.Description,
quan = sig.quantity.FirstOrDefault(),
}).ToList();
return View(model);
}
We can call each parameters of ViewModel in webgrid without using First().
WebgridSample.cshtml:
<div id="gridContent">
#grid.GetHtml(tableStyle: "webGrid",
headerStyle: "header",
alternatingRowStyle: "alt",
selectedRowStyle: "select",
columns: grid.Columns(
grid.Column("Id", ),
grid.Column("Name", " Name"),
grid.Column("Description", "Description", style: "description"),
grid.Column("Quantity", "quan "</i>)
))

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