I have a module which send data from controller to view. it has multiple rows and it shows correctly as i wanted. now after making some changes by user i am trying again to save changes in database with the help of actionresult. but when i try to fetch values it say my model is empty/null but it's not ...i am not getting what is the issue...Thanks in advance...
Here is my model:
public class ManageAppsModel
{
public string appname { get; set; }
public int id { get; set; }
public bool chkbillboard { get; set; }
}
Here is my view:
#model IEnumerable<Nd.Models.ManageAppsModel>
#using (Html.BeginForm(null, null, FormMethod.Post, new { enctype = "multipart/form-data" }))
{
<br />
<h2 style="color:#80afdd;font-size:14px;">
<strong> List of Existing Apps:</strong>
</h2>
<br />
<div class="section-copy">
<table>
#foreach (var item in Model)
{
<tr>
#if (Context.User.Identity.Name == "admin")
{
<td style="width:50px;">
#if (#item.chkbillboard == true)
{
<input name ="chk1" class="myCheckbox" type="checkbox" value="#item.chkbillboard" checked="checked" />
}
else
{
<input name ="chk2" class="myCheckbox" id="chkbox" type="checkbox" value="#item.chkbillboard" onclick="return chkbox();" />
}
</td>
}
<td style="width:200px;">
#item.appname
</td>
<td style="width:50px;">
#Html.ActionLink("Edit", "UpdateAPIForm", new { #id = item.id, appname = item.appname })
</td>
</tr>
}
</table>
</div>
<br/><br/>
if (Context.User.Identity.Name == "admin")
{
<div>
<input type="submit" name="Upload" value="Upload new flash info message" />
</div>
}
}
Here is my actionresult:
[Authorize]
public ActionResult ManageApps(String username)
{
var a = HttpContext.User.Identity.Name;
var context = new ndCorp_SiteEntities();
if (a == "admin")
{
var viewModel1 = from dc in context.DevContactInfoes
join dm in context.DevMarketplaceInfoes on dc.AppName equals dm.AppName
select new ManageAppsModel { appname = dc.AppName, id = dc.SNo, chkbillboard = dc.billboard.Value }
;
return View( viewModel1 );
}
else
{
var viewModel = from du in context.DevUserInfoes
join dc in context.DevContactInfoes on du.UserName equals dc.UserName
join dm in context.DevMarketplaceInfoes on dc.AppName equals dm.AppName
where du.UserName == a
select new ManageAppsModel { appname = dc.AppName, id = dc.SNo };
return View(viewModel);
}
}
[Authorize]
[HttpPost]
public ActionResult ManageApps(IEnumerable<ManageAppsModel> apps)
{
var user = HttpContext.User.Identity.Name;
var context = new ndCorp_SiteEntities();
foreach (var ManageAppsModel in apps)
{
if (ManageAppsModel.chkbillboard == true)
{
Response.Write("hello");
}
}
return RedirectToAction("ManageApps", new { username = user });
}
Your checkboxes are named chk1 and chk2, but your field is called chkBillboard. When you post your value, it uses the names of the input fields to match up the field names in your model.
I suggest using a helper, which makes sure you have the correct format.
#Html.CheckBoxFor(x => item.chkBillboard, new { #class="myCheckbox" })
Related
I'm trying to update my collection of users' roles in my ASP.NET Identity project, but I'm currently stuck because I'm getting a null UsersAndRolesDictionary property in the ViewModel sent to my [HttpPost] method.
Here is my ViewModel, UpdateUserRolesViewModel:
namespace Project_Name.Models
{
public class UpdateUserRolesViewModel
{
public IDictionary<ApplicationUser, ICollection<IdentityUserRole>> UsersAndRolesDictionary { get; set; } // <-- This is returning null currently
}
}
Here's my HomeController's methods:
[Authorize(Roles = "Admin")]
public ActionResult RoleManager()
{
ViewBag.Message = "Role Management Page";
var databaseContext = new ApplicationDbContext(); // Get the Database Context
var users = databaseContext.Users.Include(u => u.Roles); // Get all users from the Database and their Roles
var newDict = new Dictionary<ApplicationUser, ICollection<IdentityUserRole>>();
// Add each user and their roles to the dictionary
foreach (var user in users)
{
newDict.Add(user, user.Roles);
}
// Update the ViewModel with the collection of users and roles
var updateUserRolesViewModel = new UpdateUserRolesViewModel {UsersAndRolesDictionary = newDict};
return View(updateUserRolesViewModel);
}
[HttpPost]
[Authorize(Roles = "Admin")]
[ValidateAntiForgeryToken]
public async Task<ActionResult> UpdateUsersRolesAsync(UpdateUserRolesViewModel updateUserRolesViewModel)
{
try
{
//TODO: Attempt to update the user roles or delete the user
return View("RoleManager");
}
catch
{
//TODO: Properly catch errors
return View("RoleManager");
}
}
Here is my View, RoleManager:
#using Project_Name.Models
#model UpdateUserRolesViewModel
#{
ViewBag.Title = "Role Manager";
var databaseContext = new ApplicationDbContext(); // Get the Database Context
var roles = databaseContext.Roles; // Get all Roles from the database, use this to compare against
}
<h2>#ViewBag.Title</h2>
<div class="row">
<div class="col-lg-12 col-md-12 col-sm-12 col-xs-12">
#using (Html.BeginForm("UpdateUsersRolesAsync", "Home", FormMethod.Post))
{
#Html.AntiForgeryToken()
<div class="form-group">
<div class="table-responsive">
<table class="table table-striped table-bordered table-hover">
<thead>
<tr>
<th>Email</th>
<th>Roles</th>
<th>Delete User?</th>
</tr>
</thead>
<tbody>
#{
int i = 0; // Used to make unique IDs for the user's table row, and deleteUserCheckbox
int j = 0; // Used to make unique IDs for the role checkboxes
foreach (var user in Model.UsersAndRolesDictionary.Keys)
{
i++;
<tr id="userTableRow_#i">
<td>#user.Email</td>
<td>
#* Show each role availabe as a checkbox. Check them if the user has that role. *#
#foreach (var role in roles)
{
#Html.CheckBox("userRoleCheckbox_" + j++, user.Roles.Any(identityUserRole => identityUserRole.RoleId.Contains(role.Id)))
<span>#role.Name</span>
<br />
}
</td>
<td>
#Html.CheckBox("deleteUserCheckbox_" + i)
<span>Delete User</span>
</td>
</tr>
}
}
</tbody>
</table>
</div>
#* Reset and Submit buttons *#
<div class="col-lg-2 col-lg-push-8 col-md-2 col-md-push-8 col-sm-2 col-sm-push-8 col-xs-2 col-xs-push-8">
<input type="reset" class="btn btn-danger btn-block" value="Reset" />
</div>
<div class="col-lg-2 col-lg-push-8 col-md-2 col-md-push-8 col-sm-2 col-sm-push-8 col-xs-2 col-xs-push-8">
<input type="submit" class="btn btn-primary btn-block" value="Submit" />
</div>
</div>
}
</div>
</div>
I'm using the dictionary UsersAndRolesDictionary to collect all the users and their roles, then enumerating through that to produce my view in the form of a table.
I'm hoping to change the checkbox values of potential multiple users, then passing that updated ViewModel to my [HttpPost] UpdateUsersRolesAsync method in order to update my user roles, but right now I'm getting a null value for the UsersAndRolesDictionary property and I'm not sure why or how to fix it.
Thanks to Stephen Muecke's links/answers in the comments I was able to answer this question. See my answer post below.
Following the suggestions of Stephen Muecke in the comments, I have gotten a valid ViewModel to be returned.
Added/updated three ViewModels that combine together:
The first being RoleViewModel:
public class RoleViewModel
{
public string Id { get; set; }
public string Name { get; set; }
public bool IsSelected { get; set; }
}
Second being UserViewModel:
public class UserViewModel
{
public string Id { get; set; }
public string Email { get; set; }
public List<RoleViewModel> RoleViewModels { get; set; }
public bool DeleteUser { get; set; } // Doesn't work yet, might be in the wrong place
}
And finally the third being an updated version of UpdateUserRoleViewModel:
public class UpdateUserRolesViewModel
{
public int Id { get; set; }
public List<UserViewModel> UserViewModels { get; set; }
}
In my updated HomeController are the methods again:
[Authorize(Roles = "Admin")]
public ActionResult RoleManager()
{
ViewBag.Message = "Role Management Page";
var databaseContext = new ApplicationDbContext(); // Get the Database Context
var users = databaseContext.Users.Include(u => u.Roles).ToList(); // Get all users from the Database and their Roles
// Create the UpdateUserRolesViewModel
var updateUserRolesViewModel = new UpdateUserRolesViewModel
{
Id = 0, // Not sure what else the Id would be
UserViewModels = new List<UserViewModel>()
};
// Add each user to the UserViewModels list
for (int i = 0; i < users.Count(); i++)
{
var userViewModel = new UserViewModel
{
Id = users.AsEnumerable().ElementAt(i).Id,
Email = users.AsEnumerable().ElementAt(i).UserName,
RoleViewModels = new List<RoleViewModel>(),
DeleteUser = false
};
// Add each role from the Roles table to the RoleViewModels list, check if user has that role
foreach (var role in databaseContext.Roles)
{
var roleViewModel = new RoleViewModel
{
Id = role.Id,
Name = role.Name,
IsSelected = users.AsEnumerable().ElementAt(i).Roles.Any(identityUserRole => identityUserRole.RoleId.Contains(role.Id))
};
userViewModel.RoleViewModels.Add(roleViewModel);
}
updateUserRolesViewModel.UserViewModels.Add(userViewModel);
}
return View(updateUserRolesViewModel);
}
[HttpPost]
[Authorize(Roles = "Admin")]
[ValidateAntiForgeryToken]
public async Task<ActionResult> UpdateUsersRolesAsync(UpdateUserRolesViewModel updateUserRolesViewModel)
{
try
{
// Attempt to update the user roles
foreach (var user in updateUserRolesViewModel.UserViewModels)
{
// Delete user
//TODO: Prompt user to confirm deletion if one or more people are being deleted
if (user.DeleteUser)
{
var userToDelete = await UserManager.FindByIdAsync(user.Id); // Get the ApplicationUser object of who we want to delete
await UserManager.DeleteAsync(userToDelete); // Delete the user
continue; // Don't try to update the roles of a deleted user.
}
// Remove all roles from the User
var rolesToRemove = await UserManager.GetRolesAsync(user.Id);
await UserManager.RemoveFromRolesAsync(user.Id, rolesToRemove.ToArray());
// Add roles to the User
foreach (var roleViewModel in user.RoleViewModels.Where(r => r.IsSelected))
{
await UserManager.AddToRoleAsync(user.Id, roleViewModel.Name);
}
}
return RedirectToAction("RoleManager");
}
catch
{
//TODO: Properly catch errors
return RedirectToAction("RoleManager");
}
}
Finally, here is my View, RoleManager
#using Project_Name.ViewModels
#model UpdateUserRolesViewModel
#{
ViewBag.Title = "Role Manager";
}
#* Debugging text *#
#foreach (var user in Model.UserViewModels)
{
<div>User ID: #user.Id</div>
<div>User Name: #user.Email</div>
<p>
#foreach (var roleViewModel in user.RoleViewModels.Where(r => r.IsSelected))
{
<div>Role ID: #roleViewModel.Id</div>
<div>Role Name: #roleViewModel.Name</div>
}
</p>
<hr />
}
<h2>#ViewBag.Title</h2>
<div class="row">
<div class="col-lg-12 col-md-12 col-sm-12 col-xs-12">
#using (Html.BeginForm("UpdateUsersRolesAsync", "Home", FormMethod.Post))
{
#Html.AntiForgeryToken()
#Html.HiddenFor(m => m.Id)
<div class="form-group">
<div class="table-responsive">
<table class="table table-striped table-bordered table-hover">
<thead>
<tr>
<th>Email</th>
<th>Roles</th>
<th>Delete User?</th>
</tr>
</thead>
<tbody>
#for (int i = 0; i < Model.UserViewModels.Count; i++)
{
<tr id="userTableRow_#i">
<td>
#Html.HiddenFor(m => m.UserViewModels[i].Id)
#Html.HiddenFor(m => m.UserViewModels[i].Email)
#Model.UserViewModels[i].Email
</td>
<td>
#for (int j = 0; j < Model.UserViewModels[i].RoleViewModels.Count; j++)
{
#Html.HiddenFor(m => m.UserViewModels[i].RoleViewModels[j].Id)
#Html.HiddenFor(m => m.UserViewModels[i].RoleViewModels[j].Name)
#Html.CheckBoxFor(m => m.UserViewModels[i].RoleViewModels[j].IsSelected)
#Html.DisplayTextFor(m => m.UserViewModels[i].RoleViewModels[j].Name)
<br/>
}
</td>
<td>
#Html.CheckBoxFor(m => m.UserViewModels[i].DeleteUser)
#Html.DisplayNameFor(m => m.UserViewModels[i].DeleteUser)
</td>
</tr>
}
</tbody>
</table>
</div>
#* Reset and Submit buttons *#
<div class="col-lg-2 col-lg-push-8 col-md-2 col-md-push-8 col-sm-2 col-sm-push-8 col-xs-2 col-xs-push-8">
<input type="reset" class="btn btn-danger btn-block" value="Reset" />
</div>
<div class="col-lg-2 col-lg-push-8 col-md-2 col-md-push-8 col-sm-2 col-sm-push-8 col-xs-2 col-xs-push-8">
<input type="submit" class="btn btn-primary btn-block" value="Submit" />
</div>
</div>
}
</div>
</div>
This now updates the user's Roles, and Deletes them (though there is no confirmation check so be careful with that!)
in my journey of learning ASP.NET MVC I encounterd another difficulty:
I'm trying to POST a form with 3 checkboxes, the checkboxes are looped onto the form according to a bound PresentationModel.
I don't know what to fill in at the "asp-for" tag-helpers for the checkboxes in the view so they pass a boolean to the "Create()" ActionResult in the controller and to show the values in the "Overview" View.
Currently it passes NULL for al of them, the other aproaches I tried always resulted in an "InvalidCastException" as it has to be a boolean not an "int[]".
PresentationModel (PMRegistration.cs)
public class PMRegistration
{
public List<Device> Devices { get; set; }
}
View (Index.cshtml)
#model Week3_oef2_ITPro.PresentationModel.PMRegistration
<form asp-controller="Register" asp-action="Create" method="post">
<table>
<tr>
<td>Are you wearing any dangerous accessoires</td>
</tr>
#foreach (var item in Model.Devices)
{
<tr>
<td>#item.Name</td>
<td class="form-group">
<input type="checkbox" asp-for="#item.CheckState" value="#item.Id" class="form-control" />
</td>
</tr>
}
<tr>
<td>
<input type="submit" class="btn btn-default" />
</td>
</tr>
</table>
</form>
Model (Device.cs)
public class Device
{
public int Id { get; set; }
public string Name { get; set; }
public bool CheckState { get; set; }
}
Model (Data.cs, the Device objects get initialized here)
private static List<Device> devices = new List<Device>();
static Data()
{
devices.Add(new Device() { Id = 1, Name = "Laptop" });
devices.Add(new Device() { Id = 2, Name = "Tablet" });
devices.Add(new Device() { Id = 3, Name = "Apple Watch" });
}
public static List<Device> GetDevices()
{
return devices;
}
Controller (RegisterController.cs)
public class RegisterController : Controller
{
// GET: /<controller>/
[HttpGet]
public IActionResult Index()
{
PMRegistration pm = new PMRegistration();
pm.Devices = Data.GetDevices();
return View(pm);
}
public ActionResult Create(PMRegistration pm)
{
if (ModelState.IsValid)
{
return View("Overview", pm);
}
else
{
return RedirectToAction("Index");
}
}
}
------------ SOLVED -------------
With HTML-helpers:
#for (int i = 0; i < Model.Devices.Count; i++)
{
<tr>
<td>
#Model.Devices[i].Name
</td>
<td>
#Html.CheckBoxFor(m => Model.Devices[i].CheckState)
#Html.HiddenFor(m => Model.Devices[i].Id)
#Html.HiddenFor(m => Model.Devices[i].Name)
</td>
</tr>
}
The below code displays list of countries with checkbox for each. The intend is to save which checkbox was checked.
But when the submit button is clicked, in the method
ActionResult Index(UserModel newmodel) in the newmodel, the value of parameters SelectedSecurityGroup, SelectedSecurityObject and SecurityGroups is null.
Any idea what is wrong with this code?
In UserModel.cs
public class UserModel
{
public string SelectedSecurityGroup { get; set; }
public string SelectedSecurityObject { get; set; }
[DisplayName("Security Group")]
public virtual ICollection<SecurityGroup> SecurityGroups { get; set; }
}
public class SecurityGroup
{
public int Id { get; set; }
public string SecurityGroupName { get; set; }
public bool Active { get; set; }
}
In UserController.cs
[HttpGet]
public ActionResult Index()
{
UserModel objUserModel = new UserModel();
List<SecurityGroup> lstSecurityGroup = FillViewBag();
objUserModel.SecurityGroups = lstSecurityGroup;
return View(objUserModel);
}
[HttpPost]
public ActionResult Index(UserModel newmodel)
{
string strtest = "";
//Code to save data
return View(newmodel);
}
private List<SecurityGroup> FillViewBag(UserModel model = null)
{
List<SecurityGroup> lstSecurityGroup = new List<SecurityGroup>();
lstSecurityGroup.Add(new SecurityGroup { Id = 1, SecurityGroupName = "India", Active = true });
lstSecurityGroup.Add(new SecurityGroup { Id = 2, SecurityGroupName = "USA", Active = true });
lstSecurityGroup.Add(new SecurityGroup { Id = 3, SecurityGroupName = "Pakistan", Active = false });
lstSecurityGroup.Add(new SecurityGroup { Id = 4, SecurityGroupName = "Nepal", Active = false });
return lstSecurityGroup;
}
In Index.cshtml
#model Example.User.Web.Models.UserModel
<!DOCTYPE html>
<html>
<head>
<title>Dashboard</title>
<script src="~/Scripts/jquery-1.11.0.js"></script>
<script src="~/Scripts/jquery.unobtrusive-ajax.min.js"></script>
</head>
<body>
<div>
<div>
<div id="lists">
#Html.Partial("SecurityListsView", Model)
</div>
</div>
</div>
</body>
</html>
In SecurityListsView.cshtml
#model Example.User.Web.Models.UserModel
#using (Ajax.BeginForm("Index", "User", new AjaxOptions() { UpdateTargetId = "lists" }))
{
<table>
#{ int i = 0; }
#foreach (var item in Model.SecurityGroups )
{
<tr>
<td>
#Html.CheckBox("fileName", item.Active)
#Html.Hidden("fileId", item.Id)
</td>
<td>
#Html.DisplayFor(modelItem => item.SecurityGroupName)
</tr>
i++;
}
</table>
<input type="submit" name="btn1" value="Save" />
}
Finally got it working. Below is the corrected code:
In SecurityListsView.cshtml
#model Example.User.Web.Models.UserModel
#using (Html.BeginForm("Index", "User", "POST"))
{
<table>
#{ int i = 0; }
#foreach (var newitem in Model.SecurityGroups)
{
<tr>
<td>
#Html.CheckBoxFor(model => model.SecurityGroups[i].Active)
#Html.HiddenFor(model => model.SecurityGroups[i].Id, "Value")
</td>
<td>
#Html.DisplayFor(model => model.SecurityGroups[i].SecurityGroupName)
</tr>
i++;
}
</table>
<input type="submit" name="btn1" value="Save" />
}
Hope it helps someone! :)
I have controller for address I used it to enter multiple addresses but I want to create dropdosnlist to select the person and enter his addresses
I create this helper class in my model folder to create select item
public class PersonsSelectItems
{
public int SelectedId { get; set; }
public List<Person> Persons { get; set; }
}
I use AddressController to send the selectitem to it view
public class AddressController : Controller
{
private readonly CustomersDBEntities context = new CustomersDBEntities();
private PersonsSelectItems personsSelectItems= new PersonsSelectItems();
///get list of persones
///
public List<Person> GetPersonsList()
{
return (from c in personsSelectItems.Persons
select c).ToList();
}
//
// GET: /Address/
public ActionResult Index()
{
//var model = GetPersonsList(); //var model = GetPersonsList().Select(x => new SelectListItem
//{
// Value = x.PersonID.ToString(),
// Text = x.FirstName,
// Selected = true | false
//});
///var model = new PersonsSelectItems { Persons = GetPersonsList() };
var model = GetPersonsList();
return View(model);
}
//
// GET: /Address/Welcome/
public string Welcome()
{
return "This is the Welcome action method...";
}
[HttpPost]
public ActionResult Create(Address address)
{
//Loop through the request.forms
var Addesslist = new List<Address>();
for (int i = 1; i <= Request.Form.Count; i++)
{
var street = Request.Form["street_0" + i + ""];
var city = Request.Form["city_0" + i + ""];
var postalCode = Request.Form["postalCode_0" + i + ""];
var province = Request.Form["province_0" + i + ""];
var personID = 1;
if (street != null && city != null && postalCode != null && province != null)
{
try
{
context.Addresses.Add(new Address
{
Street = street,
City = city,
Province = province,
PostalCode = postalCode,
PersonID = personID
});
context.SaveChanges();
}
catch (Exception exc)
{
}
}
else
{
break;
}
}
return RedirectToAction("Index");
}
}
I get this expsetion
Value cannot be null. Parameter name: source
Description: An unhandled exception occurred during the execution of
the current web request. Please review the stack trace for more
information about the error and where it originated in the code.
Exception Details: System.ArgumentNullException: Value cannot be null.
Parameter name: source
Adress view
#model MVC.Models.Address
Tuple<Person,Order>
#{
ViewBag.Title = "Index";
}
<h2>Index</h2>
#using (Html.BeginForm("Create", "Address", FormMethod.Post))
{
#Html.DropDownListFor(x => x.Person, new SelectList(Model.Person, "PersonId", "FirstName"))
#Html.AntiForgeryToken()
#Html.ValidationSummary(true)
<div class="table-responsive">
<table id="address_table" class="table">
<thead>
<tr>
<th>Street</th>
<th>City</th>
<th>Province</th>
<th>PostalCode</th>
<th> </th>
</tr>
</thead>
<tbody>
<tr>
<td>
<input id="Text1" type="text" name="street_01" maxlength="255" required class="street" /></td>
<td>
<input id="Text2" type="text" name="city_01" maxlength="255" required class="city" /></td>
<td>
<input id="Text3" type="text" name="province_01" maxlength="255" required class="province" /></td>
<td>
<input id="Text4" type="text" name="postalCode_01" maxlength="7" required class="postalCode" /></td>
<td> </td>
</tr>
</tbody>
</table>
</div>
<input type="button" value="Add Row" id="add_AdressRow" class="btn btn-lg btn-success btn-block" />
<p>
<input type="submit" value="Create" />
</p>
}
<div>
#Html.ActionLink("Back to List", "Index")
</div>
#section Scripts {
#Scripts.Render("~/bundles/jqueryval")
}
just want to ask how can I bind dropDwonList using list from GetPersonsList() function
from AdressController and bind I now their are away to do it but I could not find it ?
Your problem is that you're trying to use some LINQ over a null list.
This bad boy here:
public List<Person> Persons { get; set; }
Is null. You can add a constructor to your type to initialize it:
public class PersonsSelectItems
{
public int SelectedId { get; set; }
public List<Person> Persons { get; set; }
public PersonsSelectItems() {
Persons = new List<Person>();
}
}
..and that will stop your current error.
I have to point out a couple of things though. Firstly, the naming Persons is strange. Make it an English plural of People.
Secondly, you don't actually have to use LINQ here. Your GetPersonList method can simply be:
public List<Person> GetPersonsList()
{
return personsSelectItems.Persons;
}
Even then.. you have access to that collection already. So your model assignment can be:
var model = _personsSelectItems.Persons;
I'm newbie in MVC (MVC4) and I have this problem:
I need one view to show Listbox data on left and form to add/edit on right of this view.
Problem is: when I select on listbox then click "Edit", no data to show on Edit form.
screen for this question
My View and Code are bellow:
My View Name AddZone (Addzone.cshtml):
#model CTN_MVC.Models.Zone
#{
ViewBag.Title = "AddZone";
Layout = "~/Views/Shared/_Layout.cshtml";
}
<h2>Zone Management
</h2>
<p></p>
#using (Html.BeginForm())
{
#Html.ValidationSummary(true)
<div style="float: right">
<fieldset>
<legend>AddZone</legend>
<div class="editor-label">
#Html.LabelFor(model => model.Name)
</div>
<div class="editor-field">
#Html.EditorFor(model => model.Name)
#Html.ValidationMessageFor(model => model.Name)
</div>
<div class="editor-label">
#Html.LabelFor(model => model.ParentID)
</div>
<div class="editor-field">
#Html.DropDownList("parentzone", new SelectList(new CTN_MVC.Controllers.AdminController().ShowParentZone((string)ViewBag.ParentZoneSelect), "Value", "Text"), " -- Choice Zones -- ", new { style = "width:312px" })
</div>
<p>
<button name="zoneaction" title="Update" value="zone_add" >Update</button>
</p>
</fieldset>
</div>
<div style="float: left">
#{Html.RenderPartial("ListZones");}
</div>
}
Here is ListZone.cshtml
#Html.ListBox("listzone", new CTN_MVC.Controllers.AdminController().ShowListZone((string[])ViewBag.ZoneSelect), new { size = "15", multiple = "multiple", style = "width:450px" })
<br />
<br />
<table>
<tr>
<td>
<button title="Sửa" value="zone_edit" name="zoneaction">Edit</button>
</td>
<td>
<button title="Xóa" value="zone_del" name="zoneaction">Delete</button>
</td>
</tr>
</table>
And my Code in Controller:
[Authorize]
public ActionResult AddZone()
{
return View();
}
[HttpPost]
[Authorize]
public ActionResult AddZone(Zone input, string zoneaction, string[] listzone, string parentzone)
{
if (zoneaction == "zone_del")
{
foreach (string id in listzone)
{
mghelper.Delete<Zone>(TableNames.Zone, "ZoneID", id);
}
return RedirectToAction("AddZone");
}
else if (zoneaction == "zone_edit")
{
input = mghelper.GetInfo<Zone>(TableNames.Zone, "ZoneID", listzone[0])[0];
ViewBag.ParentZoneSelect = input.ParentID.ToString();
return View("AddZone", input);
}
else
{
if(input.ZoneID > 0)
{
input.ParentID = Utility.ConvertToInt(parentzone);
input.DateCreate = DateTime.UtcNow;
input.AdminID = CurrentAdmin._id;
mghelper.Updates<Zone>(input, TableNames.Zone);
}
else
{
List<Zone> mtinfo = mghelper.GetLast<Zone>(TableNames.Zone, "DateCreate", 0);
if (mtinfo == null || mtinfo.Count < 1)
input.ZoneID = 1;
else
input.ZoneID = mtinfo[0].ZoneID + 1;
input.ParentID = Utility.ConvertToInt(parentzone);
input.DateCreate = DateTime.UtcNow;
mghelper.Insert<Zone>(input, TableNames.Zone);
}
return RedirectToAction("AddZone");
}
}
public string ZoneSelect { get; set; }
public string ParentZoneSelect { get; set; }
public IEnumerable<SelectListItem> ShowListZone(string[] id)
{
if (id == null)
{
id = new string[1];
id[0] = "0";
}
var allFlavors = GetListZone(id).Select(f => new SelectListItem
{
Value = f.ZoneID.ToString(),
Text = f.ZoneName,
Selected = f.isSelected
});
return allFlavors;
}
public class SelectZone
{
public string ZoneName { get; set; }
public string ZoneID { get; set; }
public bool isSelected { get; set; }
}
public IEnumerable<SelectListItem> ShowParentZone(string id)
{
if (id == null) id = "0";
string[] lid = new string[1];
lid[0] = id;
var allFlavors = GetListZone(lid).Select(f => new SelectListItem
{
Value = f.ZoneID.ToString(),
Text = f.ZoneName,
Selected = f.isSelected
});
return allFlavors;
}
public List<SelectZone> GetListZone(string[] lid)
{
var query = Query.EQ("ParentID", 0);
List<Zone> lz = mghelper.GetByCondition<Zone>(TableNames.Zone,query, 0,false);
List<SelectZone> lsz = new List<SelectZone>();
foreach (Zone z in lz)
{
SelectZone sl = new SelectZone();
sl.ZoneName = z.Name;
sl.ZoneID = z.ZoneID.ToString();
bool checksl = false;
foreach (string id in lid)
{
if (z.ZoneID.ToString() == id)
{
checksl = true;
}
}
sl.isSelected = checksl;
lsz.Add(sl);
//RecruiListZone(lsz, z.ZoneID, lid);
}
return lsz;
}
Please help me. (I'm sorry for my english is not good)
You need to call the GetZone when you click Edit. I believe as of now you are your form simply makes a POST to the same action which was used to load the page.
Add a new action method to return the selected zone detail
In your case, you could start using jQuery ajax and load the Partial view in the right hand side.
Below is the sample code to load zone detail
Controller
[HttpPost]
public ActionResult GetZone(string id)
{
//load your model
return PartialView("ZoneDetail.cshtml",model);
}
jQuery
$(document.ready(function(){
$('#edit-zone').click(function(){
$.post('/Zone/GetZone',{id:selectedId}, function(data){
$('#zone-detail-container').html(data);
});
});
});