How to edit data inside the WebGrid Helper - c#

I have a WebGrid full of lots of products, and I want to be able to edit the quantity for each row in the web grid and update the Cart table in the database when the textChanged event is raised on the corresponding textbox.
But is this even possible with WebGrid? I have not found anything that would suggest it's possible. I would really appreciate any help at all.

It's possible to attach a change event to the textboxes.
I set my grid up like the following:
#grid.GetHtml(
htmlAttributes: new { cellspacing = "2px", cellpadding = "2px" },
columns: grid.Columns(
grid.Column("Id"),
grid.Column("Description"),
grid.Column("PacketQuantity"),
grid.Column("ThickCover", format: (item) => {
var p = item.Value as MvcApplication1.Models.Product;
return Html.TextBox("ThickCover", p.ThickCover, new { #class = "thickCoverInput", #data_value = p.Id });
}),
grid.Column("ThinCover", format: (item) => {
var p = item.Value as MvcApplication1.Models.Product;
return Html.TextBox("ThickCover", p.ThinCover);
})
)
)
Then I had the following script to wire up the changes:
<script src="~/Scripts/jquery-1.7.1.js"></script>
<script>
$(document).ready(function () {
$('.thickCoverInput').change(function(event) {
alert(event.currentTarget.attributes["data-value"].value);
alert(event.currentTarget.value);
// Here you can post data to an action to update your table
});
});
</script>
When I changed the value in the textbox, I was able to get two alerts. One for the Id of the Product and the other is the new value.
Hope this is what you were looking for.

Related

Jquery to move items from one Listbox to another listbox

I want to move items from one listbox to another, I have a jQuery but it is not behaving properly.
When i click left in background it causes all items to move from list2 to list1 but in front end it shows that list2 have value.
when i click submit then it causes error.
List1 is source and List2 is destination
$(document).ready(function () {
$(function () {
function moveItems(origin, dest) {
$(origin).find(':selected').appendTo(dest);
}
function moveAllItems(origin, dest) {
$(origin).children().appendTo(dest);
}
$('#left').on('click', function () {
moveItems('#SelectedPanelList', '#AllPanelList');
});
$('#right').on('click', function () {
moveItems('#AllPanelList', '#SelectedPanelList');
});
$('#leftall').on('click', function () {
moveAllItems('#SelectedPanelList', '#AllPanelList');
});
$('#rightall').on('click', function () {
moveAllItems('#AllPanelList', '#SelectedPanelList');
});
});
Example Image
Suppose I have 4 items in List2--a,b,c,d but only c,d are selected then in db only c,d is getting updated but i want all items which are in list2 i.e. a,b,c,d should get updated in db. Please suggest.
Htmls:
for List 1
#Html.DropDownListFor(model => model.AllPanelList, Model.AllPanelList, new { #id = "AllPanelList", #class = "form-control", multiple = "multiple" })
For list 2
#Html.DropDownListFor(model => model.SelectedPanelListArray, Model.SelectedPanelList, new { #id = "SelectedPanelList", SelectListItem="true", #class = "form-control", multiple = "multiple" })
$('button').click(function(){
var $options = $("#selection > option").clone();
$('#copy').append($options);
})
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<select id="selection">
<option>select</option>
<option>option1</option>
<option>option2</option>
</select>
<select id="copy">
</select>
<button>copy</button>

MultiSelectList change dynamically ASP.NET MVC Razor

I'm using this code to generate a multi-select2. Tags is a MultiSelectList.
#Html.DropDownList("mail-to", (IEnumerable<SelectListItem>)ViewBag.Tags, String.Empty, htmlAttributes: new { multiple = "", #class = "form-control select2 select2-multiple" })
$("#mail-to").select2({
minimumResultsForSearch: -1,
closeOnSelect: false,
});
It works great. Now I want to change the select options with another ViewBag based on a checkbox field checked change event.
Is there a way to change select2 data populated with this type of list or a MVC way to do it?
What I've tryed:
$("#mail-to").select2({
tags: #ViewBag.TagsArea, //or tags: #Html.Raw((IEnumerable<SelectListItem>)ViewBag.TagsArea)
});
Managed to solve it:
var areas = #Html.Raw(Json.Encode(ViewBag.Tags)) ;
$("#mail-to").empty();
$.each(areas, function (index, element) {
$("#mail-to").append($('<option/>', {
value: element.Value, text: element.Text
}));
});

MVC Cascading Drop Down Not Selected When Editing

I am developing an MVC 4 web application. One of the Razor views has two drop down lists. The first drop down list is populated by the ViewModel data which is passed to the view. The secondary drop down list is populated using a JQuery and Ajax call based on the selected ID from the first drop down list (cascading).
I have this working fine, however, whenever a user wishes to edit an existing record I can't get the selected secondary drop down list value to be selected.
This is my Razor code for the two drop down lists
<div class="lbl_a">
Employer:
</div>
<div class="editor-field sepH_b">
#Html.DropDownListFor(model => model.Employer, Model.EmployerList, "Select", new { #class = "inpt_a" })
</div>
<div class="editor-label">
#Html.LabelFor(model => model.DirectorateID, "Directorate/ Service Group")
</div>
<div class="editor-field">
#Html.DropDownListFor(model => model.DirectorateID, Model.DirectorateList, "Select")
</div>
This is my JQuery code
$(document).ready(function () {
//Pre load on page load
onEmployerChange();
//Hide and show DIVS based on selection
$("#Employer").change(onEmployerChange);
function onEmployerChange() {
var dataPost = { orgID: val };
$.ajax({
type: "POST",
url: '/User/GetDirectorates/',
data: dataPost,
dataType: "json",
error: function () {
alert("An error occurred." + val);
},
success: function (data) {
var items = "";
$.each(data, function (i, item) {
items += "<option value=\"" + item.Value + "\">" + item.Text + "</option>";
});
$("#DirectorateID").html(items);
}
});
}
}
});
When a user selects a value from the first drop down list, the selected ID is passed to the GetDirectorates action within the User Controller.
This is my GetDirectorates action which returns Json data
public ActionResult GetDirectorates(string orgID)
{
if (String.IsNullOrWhiteSpace(orgID))
orgID = "0";
var Directorates = _ListService.GetListItemsByOrganisationID(Convert.ToInt32(orgID));
List<SelectListItem> directorateList = new List<SelectListItem>();
directorateList.Add(new SelectListItem() { Text = "Select", Value = "" });
foreach (var directorate in Directorates)
{
directorateList.Add(new SelectListItem() { Text = directorate.description, Value = directorate.listItemID.ToString(), Selected = false });
}
return Json(new SelectList(directorateList, "Value", "Text"));
}
Whenever the users wishes to edit an existing record I pass both the values for the first and second drop down list. Both drop down lists are populated with the proper data as expected, however, the selected value for the second drop down list is never selected.
This is a shortened version of the Edit action which the user calls when attempting to edit an existing record but shows the two drop down list selected values being passed.
public ActionResult EditNonMember(int id, string feedback, string courseDateID, string courseID)
{
//code to retrieve data here
vm.Employer = UserDetails.Employer;
vm.DirectorateID = UserDetails.DirectorateID;
return View(vm);
}
Would anyone be able to help me with this?
Thanks.
You need to get the directorate list for the saved employer id and set the DirectorateList collection and then the DirectorateID (from saved record);
public ActionResult EditNonMember(int id, string feedback, string courseDateID,
string courseID)
{
//code to retrieve data here
var userDetails=repositary.GetUserFromSomeId(id);
vm.Employers=GetEmployers();
vm.Employer = userDetails.Employer;
vm.DirectorateList=GetDirectorateListForEmployer(userDetails.Employer);
vm.DirectorateID = userDetails.DirectorateID;
return View(vm);
}
private List<SelectListItem> GetEmployers()
{
// to do : Return all employers here in List<SelectListItem>
}
private List<SelectListItem> GetDirectorateListForEmployer(int employerId)
{
// to do : Return all Directorates for the selected employer
}
This should do the trick:
var subSelect = $("#DirectorateID");
// clear the selection
subSelect.empty();
//append each option to the list
$.each(data, function (i, item) {
subSelect.append($('<option/>', {
value: item.Value,
text: item.Text
}));
});
Rather than setting it via the html method, I'm simply appending an option.
This is the method I use for cascading dropdown lists using ajax.

Cascading Dropdown MVC3 returning empty dropdown fields

I am attempting to create a cascading dropdown with MVC3. The parent dropdown is called "Category", when the user selects a Category, a child dropdown is then populated with a list of pictures that belong to that Category. I've got some code in place right now, and I am able to call the controller from the View when the user selects a category. Here is my code:
Controller:
public ActionResult Pictures(int catId)
{
var k = ((List<Picture>) ViewBag.AllPictures)
.FindAll(x => x.CategoryId == catId)
.Select(x => new
{
Value = x.PictureId,
Text = x.Title
});
return Json(k, JsonRequestBehavior.AllowGet);
}
View:
<div class="editor-field">
#Html.DropDownListFor(model => model.Picture.PictureId, Enumerable.Empty<SelectListItem>(), new { #id = "pictureFilter" })
#Html.ValidationMessageFor(model => model.Picture.PictureId)
</div>
Javascript:
<script type="text/javascript">
$('#ddlFilter').on("change", function() {
var selectedCat = $(this).val();
$.getJSON("/StoreManager/Pictures", { catId: selectedCat }, function(pictures) {
var picturesSelect = $('#pictureFilter');
picturesSelect.empty();
$.each(pictures, function(index, picture) {
picturesSelect.append($('<option/>', {
value: picture.val,
text: picture.text
}));
});
});
});
</script>
When I take a look at variable 'k', that my controller is returning. It does contain all the correct collection items for the pictures, with their respective 'value' and 'text' fields assigned. When it returns the JSON back to the View, it creates a dropdown menu with the exact number of fields that should be there, but they all contain empty data. When I inspect the element in Chrome, here is the HTML afterwards:
<option><option/>
<option><option/>
<option><option/>
<option><option/>
All help is appreciated. Any further code requested will be linked to in pastebin posts.
You have return JSON then you need to used same variables as you send from Pictures controller.
try this:
<script type="text/javascript">
$('#ddlFilter').on("change", function() {
var selectedCat = $(this).val();
$.getJSON("/StoreManager/Pictures", { catId: selectedCat }, function(pictures) {
var picturesSelect = $('#pictureFilter');
picturesSelect.empty();
$.each(pictures, function(index, picture) {
picturesSelect.append($('<option/>', {
value: picture.Value,
text: picture.Text
}));
});
});
});
</script>
or you can also check the response variable get from your Action method by using firebug console tab.

Get HTML Dropdownlist selected item in Razor Webpages

I am having some difficulty figuring out how to return the selected item in my HTML.DropDownList so that upon hitting a submit button, the selected item text will be looked up in my database. Here is what I have:
#{
var selectStaff = "Select LastName + ', ' + FirstName AS Name, StaffID From StaffList ORDER BY LastName";
var data = db.Query(selectStaff);
var items = data.Select(i => new SelectListItem {
Text = i.Name
});
}
And then in the html..
#Html.DropDownList("Select1", items)
This works fine, as my dropdownlist is appearing and is populated, but now upon hitting a submit button, I want to be able to search that text of the selected item in my database. How would I go about doing this?
If you don't bind the dropdown to a property on your view model (which would be preferable), you can still get it simply using Request.Form["Select1"] in your controller action.
If you mean that you want to be able to get the value while still on the razor page, you need to use jQuery (or other javascript) to get the value.
To get the value with jQuery:
$(document).ready(function () {
$("#YourSubmitButtonID").click(function () {
// Get the value from 'Select1'
var value = $("#Select1").val();
});
});
To do something with the value, you would have to use an ajax function, something like this:
$.ajax({
url: '#Url.Action("ActionName", "ControllerName")',
data: { valueToQuery: $("#Select1").val() },
success: function (data) {
// The data is the result
}
});
On the controller named ControllerName in this example, you'd have the code that queries the database and returns your result.
public ActionResult ActionName(string valueToQuery)
{
// Do your stuff here
return Json("your result", , JsonRequestBehavior.AllowGet);
{
I have also found THIS very interesting that May help you out!
You may also try the following Steps if you don't want to use Ajax or Json tactics:
var sql = "SELECT ProductId, ProductName FROM Products";
var data = Database.Open("Northwind").Query(sql);
var items = data.Select(i => new SelectListItem {
Value = i.ProductId.ToString(),
Text = i.ProductName
});
#Html.DropDownList("productid", items)
And Also:
var sql = "SELECT ProductId, ProductName FROM Products";
var data = Database.Open("Northwind").Query(sql);
<select name="productid">
#foreach(var row in data){
<option value="#row.ProductId">#row.ProductName</option>
}
</select>

Categories

Resources