MVC 4 WebGrid DropDownLIstFor selectedValue - asp.net-mvc-4

I have a web grid in a partial view. Each column has a display and edit mode. The display mode uses labels to display the data. When a user selects "Edit", the display mode is hidden and the edit mode is displayed. Everything works, except for the "selectValue:" in the DropDownListFor in column two. The DDLF displays the selectlist, but starts with the first value instead of using the selectedValue. I've tried every variation I can come up with. Any ideas? Thanks for taking a look at this.
#model ANet.Areas.IMS.Models.DVModel
#using System.Web.Helpers
#{var grid = new WebGrid(Model.DMRN);}
<div id="gridMRN" style=" padding:20px; " >
#grid.GetHtml(
tableStyle: "webgrid-table",
headerStyle: "webgrid-header",
footerStyle: "webgrid-footer",
alternatingRowStyle: "webgrid-alternating-row",
selectedRowStyle: "webgrid-selected-row",
rowStyle: "webgrid-row-style",
mode: WebGridPagerModes.All,
columns:
grid.Columns(
grid.Column("PK_ID", "MRN ID", format: #<text><span class="display-mode">#item.PK_ID</span><label id="lblPK_ID" class="edit-mode">#item.PK_ID</label><input type="hidden" name="PK_ID" id="PK_ID" value="#item.PK_ID" /><input type="hidden" name="fk_ID" id="fk_ID" value="#item.fk_ID" /> </text>),
grid.Column("fk_MFID", "MF", format: #<text><span class="display-mode"><label id="lblfk_MFID">#item.v_L_MF.MFN</label></span>#Html.DropDownListFor(m => m.fk_MFID, new SelectList(Model.L_MF, "Value", "Text", item.fk_MFID), new { #class = "edit-mode" })</text>, style: "webgrid-col1Width"),
grid.Column("MRN", "MRN", format: #<text> <span class="display-mode"><label id="lblMRN">#item.MRN</label></span><input type="text" id="MRN" value="#item.MRN" class="edit-mode" /></text>, style: "webgrid-col3Width"),
grid.Column("Action", format: #<text>
<button class="edit-MRN display-mode" >Edit</button>
<button class="save-MRN edit-mode" >Save</button>
<button class="cancel-MRN edit-mode" >Cancel</button>
</text>, style: "webgrid-col3Width" , canSort: false)))
</div>
<script type="text/javascript" >
$(function () {
$('thead tr th:nth-child(1), tbody tr td:nth-child(1)').hide();
$('.edit-mode').hide();
$('.edit-MRN, .cancel-MRN').on('click', function () {
var tr = $(this).parents('tr:first');
tr.find('.edit-mode, .display-mode').toggle();
$("#MRNAddFrm").toggle();
});
$('.save-MRN').on('click', function () {
var tr = $(this).parents('tr:first');
var PK_ID = tr.find("#PK_ID").val();
var fk_ID = tr.find("#fk_ID").val();
var fk_MFID = tr.find("#fk_MFID").val();
var MRN = tr.find("#MRN").val();
tr.find("#lblPK_ID").text(PK_ID);
tr.find("#lblfk_ID").text(fk_ID);
tr.find("#lblfk_MFID").text(fk_MFID);
tr.find("#lblMRN").text(MRN);
tr.find('.edit-mode, .display-mode').toggle();
var MRM =
{
"PK_ID": PK_ID,
"fk_ID": fk_ID,
"fk_MFID": fk_MFID,
"MRN": MRN
};
$.ajax({
url: '/IMS/EditMRN/',
datatype: 'json',
data: JSON.stringify(MRN),
type: 'POST',
contentType: 'application/json; charset=utf-8'
})
.success(function (data) {
$('#gridMRN').replaceWith(data);
});
$("#MRNAddFrm").toggle();
});
})
</script>
ViewModel
using IMSModel;
namespace ANet.Areas.IMS.Models
{
public class DVModel
{
private IMSEntities db = new IMSEntities();
public DVModel()
{
//Define default values here
this.PageSize = 10;
this.NumericPageCount = 10;
}
....
[Display(Name = "MF")]
public int fk_MFID { get; set; }
[Display(Name = "MRN")]
public Nullable<int> MRN { get; set; }
....
public SelectList L_MF { get; set; }
..... other selectlists
public IEnumerable<v_L_MF> v_L_MF { get; set; }
..... other ienumerables lists
//Sorting-related properties
public string SortBy { get; set; }
public bool SortAscending { get; set; }
public string SortExpression //requires using System.Linq.Dynamic; on the controller
{
get
{
return this.SortAscending ? this.SortBy + " asc" : this.SortBy + " desc";
}
}
//Paging-related properties
public int CurrentPageIndex { get; set; }
public int PageSize { get; set; }
public int PageCount
{
get
{
return Math.Max(this.TotalRecordCount / this.PageSize, 1);
}
}
public int TotalRecordCount { get; set; }
public int NumericPageCount { get; set; }
}
}
Method that loads the view model
private DVModel GetDVModel(int id)
{
var _viewModel = new DVModel
{
.... other lists
v_L_MF = unitOfWork.MFRepository.Get().OrderBy(o => o.MFN),
.... other lookup lists
L_MF = new SelectList(unitOfWork.MFRepository.Get().OrderBy(o => o.MFN), "PK_MFID", "MFN", String.Empty),
};
return _viewModel;
}

Your DropdownlistFor calling will the issue.
Please lets check the follwing site.
You should give the default value on dropdownlist level, and not on select list level.
I dont remember correctly the real calling but something like this should be tryied:
#Html.DropDownListFor(m => m.fk_MFID, new SelectList(Model.L_MF, "Value", "Text", item.fk_MFID), new { #class = "edit-mode" }, "Default value")

Related

SelectList not returning the value of text only returns ID

I am quite new to asp net core and am trying to implement a select list while passing values from view to controller. All else is working fine only problem I am facing is only the ID is being passed to controller and not the text/name.
Can someone tell me where I am going wrong? Below is my code.
View Snippet
<div class="form-group">
<label>Financial Year</label>
<select asp-for="FinancialYear" asp-items="ViewBag.FinancialYear" class="selectpicker" data-dropup-auto="false" data-size="5">
</select>
</div>
Model Snippet
public class VMOM
{
public int FinancialYear { get; set; }
}
public class VMDropDown
{
public int ID { get; set; }
public string Text { get; set; }
}
Controller Snippet
[HttpGet]
public IActionResult Create()
{
VMOM vmOM = new VMOM();
ViewBag.FinancialYear = new SelectList(GetFinancialYearList(), "ID", "Text", 0).ToList();
return View(vmOM);
}
[HttpPost]
public IActionResult Create(VMOM vmOM)
{
return View(vmOM);
}
private List<VMDropDown> GetFinancialYearList()
{
List<VMDropDown> vmDropdowns = new List<VMDropDown>
{
new VMDropDown() { ID = 1, Text = "2019" },
new VMDropDown() { ID = 2, Text = "2020" }
};
return vmDropdowns;
}
A SS of the values received in action method; note that in Financial Year only the ID of the year is being diplayed and not the text value i.e, 2020
If you don't mind a little bit of javascript you can easily achieve what you want.
We add a hidden input field where its value is updated on the select change.
So when we submit the form, the hidden input's value will be submitted and binded with our model (See screenshot below).
Razor:
<form asp-action="Post" method="post">
<select class="form-control" asp-items="#ViewBag.List" asp-for="#Model.Id" id="FYear">
</select>
<input type="hidden" id="FYearText" asp-for="#Model.Year" readonly="readonly" hidden/>
<button type="submit" class="btn btn-success">Submit</button>
</form>
Model
public class VMOM
{
public int Id { get; set; }
public string Year { get; set; }
}
Controller:
[HttpGet]
public IActionResult Index()
{
var data = new List<VMOM> {
new VMOM { Id = 1, Year = "2018" },
new VMOM { Id = 2, Year = "2019" },
new VMOM { Id = 3, Year = "2020" },
new VMOM { Id = 4, Year = "2077" }
};
ViewBag.List = new SelectList(data, "Id", "Year");
return View("Index", new VMOM());
}
JS
$(document).ready(function(){
$("#FYear").on("change", function(){
$("#FYearText").val($(this).find("option:selected").text());
});
});
Result:
P.S, I am using jQuery in this example for brevity.
The simplest way is changing the ID value the same as the Text.
List<VMDropDown> vmDropdowns = new List<VMDropDown>
{
new VMDropDown() { ID = 2019, Text = "2019" },
new VMDropDown() { ID = 2020, Text = "2020" }
};

How to set default value for a model property which is displayed in a #Html.DropDownList

#model ProjectName.Models.ViewModel
var abc = (IEnumerable<SelectListItem>)ViewData["abc"];
The abc stores all retrieved records and then it displays them via the following html tag:
#Html.DropDownList("abcID", abc , "Select abc ", new { #class = "form-control", required = "required" })
I need to set default value for abcId inside the #Html.DropDownList. How can I do it?
You can refer to the link,Here is a demo worked:
Controller:
public IActionResult SendReport()
{
List<SelectListItem> listAdmin = new List<SelectListItem>();
listAdmin.Add(
new SelectListItem
{
Text = "admin1",
Value = "1"
});
listAdmin.Add(
new SelectListItem
{
Text = "admin2",
Value = "2"
});
ViewBag.listAdmin = listAdmin;
//ViewData["listAdmin"] = listAdmin;
Admin admin = new Admin { id = "2", name = "admin2" };
return View(admin);
}
Admin.cs:
public class Admin
{
public string id { get; set; }
public string name { get; set; }
}
View:
#model Admin
#{
ViewData["Title"] = "SendReport";
}
<h1>View</h1>
<div>
#Html.DropDownListFor(Model => Model.id, new SelectList((IEnumerable<SelectListItem>)ViewBag.listAdmin, "Value", "Text", Model.id), "Selecte", new { #class = "form-control", required = "required" })
</div>
Result:

Asp.net MVC Core giving null checkbox data instead of all selected checkboxes on HTTPPost

I am trying to bind list of checkboxes.On Post Model showng the value of Job_Type as 0 .It should return all selected checkboxes.Which in my case not doing so .After hours of searching I havn't found any solution.
This is the relevent part of code in my view
<div class="form-group">
#foreach (var item in Model.Job_Type)
{
<input name="Job_Type" value="#item.valID" type="checkbox" checked="#item.IsChecked"/>
#item.text <br/>
}
</div>
My Controller:
// GET: Jobs/Create
public IActionResult Create()
{
NewJob newJob = new NewJob();
List<CheckBoxModel> chkVisatype = new List<CheckBoxModel>()
{
new CheckBoxModel {valID=1, text="ASp",IsChecked=true },
new CheckBoxModel {valID=1,text="ss",IsChecked=true },
new CheckBoxModel {valID=1,text="aa",IsChecked=true },
new CheckBoxModel {valID=1,text="dd",IsChecked=true },
};
List<CheckBoxModel> chkJobtype = new List<CheckBoxModel>()
{
new CheckBoxModel {valID=1,text="ASp",IsChecked=true },
new CheckBoxModel {valID=1,text="tt",IsChecked=true },
new CheckBoxModel {valID=1,text="ss",IsChecked=true },
new CheckBoxModel {valID=1,text="aa",IsChecked=true },
};
newJob.Job_Type = chkJobtype;
newJob.Visa_Type = chkVisatype;
return View(newJob);
}
// POST: Jobs/Create
// To protect from overposting attacks, please enable the specific properties you want to bind to, for
// more details see http://go.microsoft.com/fwlink/?LinkId=317598.
[HttpPost]
[ValidateAntiForgeryToken]
public async Task<IActionResult> Create([Bind("JobID,Job_Title,AddedDate,Primary_Technology,MPTJob_Length,MPTJobLengthSelection,SPTJob_Length,SPTJobLengthSelection,Job_Length,JobLengthSelection,Secondary_Technology,Description,PossibiltyForExtenshion,Email,CC_Email,URL,City,State,Country,ZipCode,Employment_Type,Job_Type,Compensation,JobExperienceLevel,Visa_Type")] NewJob newJob)
{
if (ModelState.IsValid)
{
newJob.AddedDate = DateTime.Now;
_context.Add(newJob);
await _context.SaveChangesAsync();
return RedirectToAction(nameof(Index));
}
return View(newJob);
}
My Model:
public class CheckBoxModel
{
[Key]
public int valID { get; set; }
public string text { get; set; }
public bool IsChecked { get; set; }
}
public class NewJob
{
public List<CheckBoxModel> Job_Type { get; set; }
}
If you check the request in browser Network tab, you would find only valID of checked options are sent via form data, like below. So Job_Type property is not successfully bound, which cause the issue.
If possible, you can dynamically generate expected data based on checked options, and then submit the data using jQuery AJAX etc.
In View page
#foreach (var item in Model.Job_Type)
{
<input name="Job_Type" value="#item.valID" type="checkbox" checked="#item.IsChecked" />
<span>#item.text</span>
<br />
}
Make ajax request
function myCreateFunc() {
var job_title = $('input[name="Job_Title"]').val();
var job_type = [];
$('input[name="Job_Type"]:checked').each(function (i,el) {
job_type.push({ "valID": $(el).val(), "text": $(el).next("span").text(), "IsChecked": true });
});
var job_data = { "Job_Title": job_title, "Job_Type": job_type };
$.ajax({
url: "/Home/Create",
type: 'POST',
contentType: "application/json; charset=utf-8",
data: JSON.stringify(job_data),
success: function (response) {
//code logic here
}
});
}
In controller action (with [FromBody] attribute)
[HttpPost]
public IActionResult Create([FromBody][Bind("JobID, Job_Title, Job_Type")]NewJob newJob) //in my testing sample, only define JobID, Job_Title, Job_Type properties
Test Result
Well I tired this and it works for me.
All we need to understand how checkboxes post their data. if they have a name attribute, when checked, they post name=value.If you want to get complete list posted back it would be:
#for (int i = 0; i < Model.Job_Type.Count(); i++)
{
<input hidden asp-for="Job_Type[i].valID" />
<input hidden asp-for="Job_Type[i].text" />
<input asp-for="Job_Type[i].IsChecked" type="checkbox" />
#Model.Job_Type[i].text<br />
}

MVC Core DropDownList selected value ignored

I am trying to access my page at: https://localhost:44319/Analyze/Index/6
The problem is that my drop down list always selects the first item in the list instead of the one provided by ID. While stepping through the debugger, before the View() is returned, I see that the SelectList was populated correctly.
AnalyzeController.cs
public IActionResult Index(int? Id)
{
return Index(Id ?? getStatementEndingById(Id).StatementEndingId);
}
[HttpPost]
public IActionResult Index(int StatementEndingId)
{
var statementEnding = getStatementEndingById(StatementEndingId);
ViewBag.StatementEndingId = new SelectList(
_context.StatementEnding.OrderByDescending(s => s.StatementEndingId),
"StatementEndingId",
"Name",
statementEnding);
return View(getPayments(statementEnding));
}
private StatementEnding getStatementEndingById(int? statementEndingId)
{
StatementEnding statementEnding;
if (statementEndingId.HasValue)
{
statementEnding = _context.StatementEnding.FirstOrDefault(s => s.StatementEndingId == statementEndingId);
}
else
{
statementEnding = _context.StatementEnding.OrderByDescending(s => s.StatementEndingId).FirstOrDefault();
}
return statementEnding;
}
Setting DropDownList in Razor
#Html.DropDownList("StatementEndingId", null, new { #class = "form-control mb-2 mr-sm-2" })
I am using ASP.NET Core 2.1.
Any suggestions are much appreciated. Thanks in advance.
First i would recomend to create a typed model, something like this one :
public class StatementViewModel
{
public int StatementEndingId { get; set; }
public List<SelectListItem> StatementEndings { get; set; }
}
Second fill the Model with all dropdown options (StatementEndings) and the selected one (StatementEndingId)
public IActionResult Index()
{
var model = new StatementViewModel();
model.StatementEndingId = getStatementEndingById(Id).StatementEndingId;
model.StatementEndings = _context.StatementEnding.OrderByDescending(s => s.StatementEndingId).Select(p => new SelectListItem() { Text = p.Name, Value = p.StatementEndingId }).ToList();
return View(model);
}
And for the last, in the view
#model StatementViewModel
#Html.DropDownListFor(m => m.StatementEndingId, Model.StatementEndings, null, new { #class = "form-control mb-2 mr-sm-2" })

ASP.Net MVC - cannot set value of #Html.Checkbox after changing dropdownlist

I've looking all over for something similar, couldn't find nothing..
I'm using ASP.NET MVC 4. I'm building a page so the users in my app can manage the permissions associated with each role.
So i have a view with #htmlDropDownList to show all the available roles, and below, one #Html.CheckBox for each Permission of the role wich is selected above.
The first time the view is rendered, the checkboxes are all set to true or false, according to the permission of that role.All is fine, life is good :) . When the value of the drop is changed, i post the SelectedRoleId using $.ajax. Then, i fetch all the permissions of the new selected role.
While in debug, in the razor view, i can confirm the new values (true or false) inside the model are correct. The problem is that the checkboxes show the old values, before the role was changed..
This is my first question asked, so i'll have to apologize if the question is not being made the best way.
And thx in advance to all of you :)
So here's my Controller:
public ActionResult Index(int ? SelectedRoleId)
{
ManagePermissionsViewModel model = new ManagePermissionsViewModel();
if (SelectedRoleId == null)
{
model.SelectedRoleID = 1; // value 1 is the supervisor Role
}
else
{
model.SelectedRoleID = SelectedRoleId;
}
//values for the dropdownlist of Roles
var items = from x in db.UserRoles
select x;
model.RoleList = new SelectList(items, "Id", "DESCRIPTION");
//gets all the permissions of the selected role
model.EntirePermissionList = (from k in db.Permissions
select new Permission
{
IdPermission = k.Id,
PermissionDescription = k.Description,
IsSet = db.RolePermissions.Any(n => n.RoleId == model.SelectedRoleID && n.PermissionId == k.Id),
PermissionGroupId = (int)k.PermissionGroupId
}).ToList();
//Gets all the groups of Permissions
model.ListPermissionGroups = (from l in db.PermissionGroups
select new PermissionGroup
{
Id = l.Id,
Description = l.Description
}).ToList();
return View(model);
}
[HttpPost]
public ActionResult Index(FormCollection form) {
switch (form["SubmitButton"])
{
case "Save":
SavePermissions();
break;
default:
return RedirectToAction("Index", new RouteValueDictionary(new { controller = "ManagePermissions", action = "Index", SelectedRoleId = Convert.ToInt32(form["SelectedRoleId"]) }));
}
return View();
}
And here is my View:
'#model AML.Web.Models.ManagePermissionsViewModel
#using (Html.BeginForm("Index", "ManagePermissions", FormMethod.Post, new { id = "MyForm" }))
{
#Html.Label("Role :", htmlAttributes: new { #class = "control-label col-md-2" })
#Html.DropDownList("RoleId", Model.RoleList, new { id = "RoleId" })
<div>
#foreach (var item in Model.ListPermissionGroups)
{
<h3> #item.Description</h3>
foreach (var permission in Model.EntirePermissionList.Where(n => n.PermissionGroupId == item.Id))
{
<h5>
#permission.PermissionDescription
#Html.CheckBox("Chk_Permisssion", permission.IsSet)
</h5>
}
}
</div>
<input type="submit" value="Save" name="SubmitButton" class="btn btn-default" />
}
#section Scripts {
<script type="text/JavaScript">
$(document).ready(function () {
$("#RoleId").change(function (e) {
e.preventDefault();
$.ajax({
url: "/ManagePermissions/Index",
cache: false,
type: "POST",
data: { 'SelectedRoleId': $(this).val() },
dataType: "json",
success: function (result) { console.log("Sucess!"); },
error: function (error) { console.log("Error!"); }
})
});
});
</script>
}
And my viewModel:
public class ManagePermissionsViewModel
{
public int? SelectedRoleID { get; set; }
public string SelectedRoleDescription { get; set; }
public SelectList RoleList { get; set; }
public List<Permission> EntirePermissionList { get; set; }
public List<PermissionGroup> ListPermissionGroups { get; set; }
}
public class Permission
{
public int IdPermission { get; set; }
public bool IsSet { get; set; }
public string PermissionDescription { get; set; }
public int PermissionGroupId { get; set; }
}
public class PermissionGroup {
public int Id { get; set; }
public string Description{ get; set; }
}
UPDATE 1 -
Well, i think i got it. Let me post my approach
In the View:
#Html.DropDownListFor(n => n.SelectedRoleID, Model.RoleList,null,
new { onchange = "document.location.href = '/ManagePermissions/Index?SelectedRoleId=' + this.options[this.selectedIndex].value;" })
<div>
#foreach (var item in Model.ListPermissionGroups)
{
<h3> #item.Description</h3>
foreach (var permission in Model.EntirePermissionList.Where(n => n.PermissionGroupId == item.Id))
{
<h5>
#permission.PermissionDescription
<input type="checkbox" id="#permission.IdPermission" checked="#permission.IsSet">
</h5>
}
}
</div>
And in the Controller:
public ActionResult Index(int? SelectedRoleId)
{
ManagePermissionsViewModel model = new ManagePermissionsViewModel();
ModelState.Clear();
if (SelectedRoleId == null)
{
model.SelectedRoleID = 1;
}
else
{
model.SelectedRoleID = SelectedRoleId;
}
var items = from x in db.UserRoles
select x;
model.RoleList = new SelectList(items, "Id", "DESCRIPTION");
model.EntirePermissionList = (from k in db.Permissions
select new Permission
{
IdPermission = k.Id,
PermissionDescription = k.Description,
IsSet = db.RolePermissions.Any(n => n.RoleId == model.SelectedRoleID && n.PermissionId == k.Id),
PermissionGroupId = (int)k.PermissionGroupId
}).ToList();
model.ListPermissionGroups = (from l in db.PermissionGroups
select new PermissionGroup
{
Id = l.Id,
Description = l.Description
}).ToList();
ModelState.Clear();
return View(model);
}
Now each time the Drop changes value, the permissions in the checkboxes are updated. I got it to work with the attribute on the drop, "on change = Document.location.hef = URL". Is this a good approach? Or should i use something like ajax request ?
UPDATE 2
The Controller:
public async Task<ActionResult> Index(int? SelectedRoleId)
{
if (SelectedRoleId == null)
{
SelectedRoleId = 1;
}
var model = await GetSelectedPermissions(SelectedRoleId);
return this.View("Index",model);
}
[HttpGet]
public async Task<ActionResult> GetPermissions(string Id)
{
var SelectedRoleId = int.Parse(Id);
var model = await this.GetSelectedPermissions(SelectedRoleId);
return PartialView("_ManagePermissions", model);
}
private async Task<ManagePermissionsViewModel> GetSelectedPermissions(int? SelectedRoleId)
{
ModelState.Clear();
ManagePermissionsViewModel model = new ManagePermissionsViewModel();
model.SelectedRoleID = SelectedRoleId;
var items = from x in db.UserRoles
select x;
model.RoleList = new SelectList(items, "Id", "DESCRIPTION");
model.EntirePermissionList = await (from k in db.Permissions
select new Permission
{
IdPermission = k.Id,
PermissionDescription = k.Description,
IsSet = db.RolePermissions.Any(n => n.RoleId == model.SelectedRoleID && n.PermissionId == k.Id),
PermissionGroupId = (int)k.PermissionGroupId
}).ToListAsync();
model.ListPermissionGroups = await (from l in db.PermissionGroups
select new PermissionGroup
{
Id = l.Id,
Description = l.Description
}).ToListAsync();
return model;
}
The View
<h2>Permissions - Ajax with Partial View</h2>
#using (Html.BeginForm("SaveData", "ManagePermissions", FormMethod.Post, new { id = "MyForm" }))
{
#Html.Label("Role :", htmlAttributes: new { #class = "control-label col-md-2" })
#Html.DropDownListFor(n => n.SelectedRoleID, Model.RoleList, null, null)
<div id="target">
#Html.Partial("~/Views/Shared/_ManagePermissions.cshtml", Model)
</div>
<input type="submit" value="Save" name="SubmitButton" class="btn btn-default" />
}
#section Scripts {
<script type="text/javascript">
$(document).ready(function () {
$("#SelectedRoleID").change(function () {
var SelectedRoleID = $("#SelectedRoleID").val();
$("#target").load('#(Url.Action("GetPermissions","ManagePermissions",null, Request.Url.Scheme))?Id=' + SelectedRoleID);
});
});
</script>
}
And the Partial View:
<div>
#foreach (var item in Model.ListPermissionGroups)
{
<h3> #item.Description</h3>
foreach (var permission in Model.EntirePermissionList.Where(n => n.PermissionGroupId == item.Id))
{
<h5>
#permission.PermissionDescription
<input type="checkbox" id="#permission.IdPermission" checked="#permission.IsSet">
</h5>
}
}
</div>