ASP.Net MVC - cannot set value of #Html.Checkbox after changing dropdownlist - asp.net-mvc-4

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>

Related

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

(ModelState.IsValid) Property is not working properly in asp.net mvc4 with entity framework

I have tried simple user log in using asp.net mvc4. I have used this condition (ModelState.IsValid), It was workiing before two days. Now i am trying to execute this program, But that property is terminating the condition. Please anyone help me to rectify this problem.
This is my controller code
{
[HttpPost]
[AllowAnonymous]
public ActionResult LogIn(Project.Models.Tbl_Users user)
{
int userid = user.UserID;
var sessionid = Session["userid"];
Session["RoleId"] = user.RoleId;
Session["Username"] = user.UserName;
var sessionval = Session["Username"].ToString();
if (!ModelState.IsValid)
{
if (Isvalid(user.UserName, user.UserPassword))
{
var db = new Project.Models.EntitiesContext();
var userroleid = db.Tbl_Users.FirstOrDefault(u => u.UserName == user.UserName);
Session["RoleId"] = userroleid.RoleId;
int sessionroleid = Convert.ToInt32(Session["RoleId"]);
FormsAuthentication.SetAuthCookie(user.UserName, false);
string sessionusername = Session["Username"].ToString();
if (sessionroleid == 1)
{
return RedirectToAction("adminpage", "LogIn");
}
else
if(sessionroleid==2)
{
return RedirectToAction("teammanager", "LogIn");
}
else
{
return RedirectToAction("userpage", "LogIn");
}
}
return View(sessionval);
}
return View();
}
private bool Isvalid(string username, string password)
{
bool Isvalid = false;
using(var db = new Project.Models.EntitiesContext())
{
var user = db.Tbl_Users.FirstOrDefault(u => u.UserName == username);
var pass = db.Tbl_Users.FirstOrDefault(u => u.UserPassword == password);
if (username != null)
{
try
{
if (user.UserName == username)
{
if (pass.UserPassword == password)
{
Isvalid = true;
//Session["RoleId"] = user.RoleId;
//int sessionid = Convert.ToInt32(Session["RoleId"]);
}
}
}
catch
{
//Response.Write("Login Failed For The User");
Isvalid = false;
}
}
}
}
This is my model
{
[Required(ErrorMessage = "User Name is Invalid")]
[StringLength(200)]
[Display(Name = "User Name")]
public string UserName { get; set; }
[Required(ErrorMessage = "Password Field is Invalid")]
[StringLength(50, MinimumLength = 6)]
[DataType(DataType.Password)]
[Display(Name = "Password")]
public string UserPassword { get; set; }
[Display(Name = "Remember me?")]
public bool RememberMe { get; set; }
}
This is my view code
{
<form method="post" id="signin" action="#Url.Action("LogIn", "LogIn")">
<body style="background-color: Gray;">
<div>
<div>
</div>
#if (!Request.IsAuthenticated)
{
<strong>#Html.Encode(User.Identity.Name)</strong>
#Html.ActionLink("Log Out", "LogOut", "LogIn")
}
else
{
<fieldset>
<div>#Html.LabelFor(u => u.UserName)</div>
<div>#Html.TextBoxFor(u => u.UserName)
#if (Request.IsAuthenticated)
{
#Html.ValidationMessageFor(u => u.UserName)
#*#Html Session["Username"] = #Html.TextBoxFor(u => u.UserName);*#
}
</div>
<div>#Html.LabelFor(u => u.UserPassword)</div>
<div>#Html.PasswordFor(u => u.UserPassword)
#Html.ValidationMessageFor(u => u.UserPassword)
</div>
<div>#Html.CheckBoxFor(u => u.RememberMe)
#Html.LabelFor(u => u.RememberMe, new { #class = "checkbox" })
</div>
<div>
#Html.ValidationSummary(true, "Login Failed")
</div>
<input type="submit" value="LogIn"/>
</fieldset>
}
</div>
</body>
</form>
}
please DEBUG your code.
past this code below, just above if(!ModelState.IsValid)
var propertiesWithErrors = ModelState.Where(state => state.Value.Errors.Any()).Select(state => state.Key);;
propertiesWithErrors will give you the list of properties that has validation errors.

MVC 4 multiple buttons in form - why isn't this code working

I am trying to use a variation of the code from this page:
Multiple button in MVC
But everytime I click on the buttons it goes to the index actionresult method and not one of the button methods. Index is the view name but the button clicks are happening in a partial view called "P_NewPersonForm.cshtml"
P_NewPersonForm.cshtml
#using (Html.BeginForm())
{
<div id="divClaimType">
#Html.Label("Claim type:")
#Html.DropDownListFor(m => m.modelClaim.ClaimType, new List<SelectListItem>
{
new SelectListItem{ Text="Legal", Value = "Legal" },
new SelectListItem{ Text="Immigration", Value = "Immigration" },
new SelectListItem{ Text="Housing", Value = "Housing" }
})
</div>
<div id="divClaimStatus" style="padding: 5px;">
#foreach(var item in Model.LinkerStatusOfClaim)
{
#Html.Label("Claim status:")
#Html.DropDownListFor(m => m.LinkerStatusOfClaim[0].ClaimStatusID, new SelectList(Model.modelClaimStatus, "ClaimStatusID", "ClaimStatus"))
#Html.LabelFor(m => m.LinkerStatusOfClaim[0].Notes)
#Html.TextAreaFor(m => m.LinkerStatusOfClaim[0].Notes)
#Html.LabelFor(m => m.LinkerStatusOfClaim[0].StartDate)
#Html.TextBoxFor(m => m.LinkerStatusOfClaim[0].StartDate, new { #id = "datepicker", #Value = DateTime.Now, #readonly = true, Style = "background:#cccccc;" })
<br />
#Html.ValidationMessageFor(model => model.LinkerStatusOfClaim[0].StartDate)
<br />
}
<input type="submit" value="Add another status to this claim..." name="action:add"/>
<input type="submit" value="Delete status." name="action:remove"/>
#* #Ajax.ActionLink("Add another status to this claim...", "AddClaim", "Client", new AjaxOptions { HttpMethod = "POST"})*#
</div>
}
</div>
I have one button for adding to the collection of claims and another to remove one from the collection.
ClientController
public ActionResult Index()
{
var Model = new modelPersonClaim();
// Add one item to model collection by default
LinkerStatusOfClaim LinkerStatusOfClaim = new LinkerStatusOfClaim();
Model.LinkerStatusOfClaim.Add(LinkerStatusOfClaim);
DataLayer.RepositoryClient RC = new RepositoryClient();
Model.isValidModel = true;
RC.GetClaimTypes(Model, PersonTypes.NewPerson.ToString());
return View(Model);
}
[HttpPost]
public ActionResult P_NewPersonForm(modelPersonClaim Model)
{
DataLayer.RepositoryClient RC = new RepositoryClient();
RC.GetClaimTypes(Model, PersonTypes.NewPerson.ToString());
Model.isValidModel = ModelState.IsValid;
if (ModelState.IsValid)
{
RC.CreatePerson(Model);
Model.SuccessfulInsert = true;
Model.InsertString = "Person data has been successfully inserted into the database.";
if (Model.modelClaim.ClaimMade)
{
RC.CreateClaim(Model);
}
}
else
{
Model.SuccessfulInsert = false;
Model.InsertString = "Person data could not be inserted into the database. Missing key fields.";
}
return View("Index", Model);
}
[AttributeUsage(AttributeTargets.Method, AllowMultiple=false, Inherited = true)]
public class MultiButtonAttribute : ActionNameSelectorAttribute
{
public string Name { get; set; }
public string Argument { get; set; }
public override bool IsValidName(ControllerContext controllerContext, string actionName, MethodInfo methodInfo)
{
var isValidName = false;
var keyValue = string.Format("{0}:{1}", Name, Argument);
var value = controllerContext.Controller.ValueProvider.GetValue(keyValue);
if (value != null)
{
controllerContext.Controller.ControllerContext.RouteData.Values[Name] = Argument;
isValidName = true;
}
return isValidName;
}
}
[HttpPost]
[MultiButtonAttribute(Name = "action", Argument = "Add another status to this claim...")]
public ActionResult AddClaimStatus(modelPersonClaim Model)
{
Model.LinkerStatusOfClaim.Insert(Model.LinkerStatusOfClaim.Count, new LinkerStatusOfClaim());
return View("Index", Model);
}
[HttpPost]
[MultiButtonAttribute(Name = "action", Argument = "Delete status.")]
public ActionResult RemoveClaimStatus(modelPersonClaim Model)
{
// Can't remove IF only 1
if (Model.LinkerStatusOfClaim.Count == 1)
{
}
else
{
Model.LinkerStatusOfClaim.RemoveAt(Model.LinkerStatusOfClaim.Count);
}
return View("Index", Model);
}
When I click one the buttons it hits the public override bool IsValidName twice. Once for each button. But then because the action name is always index, it goes to the index method and not one of the button methods.
Does anyone have any ideas how to fix this?
Something is wrong with this part:
var keyValue = string.Format("{0}:{1}", Name, Argument);
var value = controllerContext.Controller.ValueProvider.GetValue(keyValue);
Your attribute is this:
[MultiButtonAttribute(Name = "action", Argument = "Add another status to this claim...")]
So in that case keyValue will become: "action:Add another status to this claim..." while your HTML states: <input type="submit" value="Add another status to this claim..." name="action:add"/>, so I think Argument in your attribute should be add.

MVC 4 WebGrid DropDownLIstFor selectedValue

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