string array to be separated with comma - asp.net-mvc-3

I had a string array which I want it to be returned in view separated by comma.
#Html.DisplayFor(m => name.studentName) <span>, </span>}
I'm using this way but the last string will ended with a comma also. Wondering how to avoid this?

I assume that you have a collection of students on your model each possessing a studentName property that you want to display:
public IEnumerable<Student> Students { get; set; }
And inside your view you are looping through this collection and displaying each student name individually.
Now instead of looping you could do the following:
#Html.Raw(
string.Join(
"<span>,<span>",
Model.Students.Select(x => Html.Encode(x.studentName))
)
)
or even better, externalize this logic into a reusable custom HTML helper:
public static class HtmlExtensions
{
public static IHtmlString FormatStudentNames(this HtmlHelper htmlHelper, IEnumerable<Student> students)
{
return new HtmlString(
string.Join(
"<span>,<span>",
students.Select(x => Html.Encode(x.studentName))
)
);
}
}
and then inside your view simply call this helper:
#Html.FormatStudentNames(Model.Students)
You no longer need to write any foreach or whatever loops you are writing.

Try
#string.Join(",", name.studentName);
And have a look at string.Join on MSDN.

$(".category").change(function () {
var value = $(this).val();
loadSubCategory(value)
});
function loadSubCategory(parentID) {
var $el = $("#SubCats");
$el.prop("disabled", true);
$el.empty();
$.ajax({
cache: false,
url: "/Category/loadSubCategory?id=" + parentID,
success: function (data) {
if (data != '' && data != null) {
if (data != 'error') {
var sch = JSON.parse(data);
if (sch.length > 0) {
$el.prop("disabled", false);
for (i = 0; i < sch.length; i++) {
$el.append($("<option></option>")
.attr("value", sch[i].ID).text(sch[i].Description));
}
}
}
}
}
});
}
public ActionResult loadSubCategory(string id)
{
string list = "";
try
{
list = Newtonsoft.Json.JsonConvert.SerializeObject(menu.SubCategory(id));
}
catch (Exception ex)
{
}
return Content(list);
}
public List<CategoryModel> SubCategory(string parentID){
List<CategoryModel> listCategory= new List<CategoryModel>();
string[] yourValues = parentID.Split(',');
foreach (var item in yourValues)
{
var Category = UowObj.CategoryRepository.Get(filter: c => c.ParentId.ToString() == item && c.IsActive == true).ToList();
if (Category != null)
{
var category= new CategoryModel();
foreach (var itemq in Category)
{
category.ID = itemq.ID;
category.Description = itemq.Description;
}
listCategory.Add(merchant);
}
}

Related

Load data in Telerik grid by dropdownlist selected value

I am a beginner in Telerik Grid in ASP.NET MVC3. I try to bind Grid with dropdownlist selected value. Please see my code below.
My web model class
public class CustomerEventRolesModels
{
public int Event { get; set; }
public IEnumerable<System.Web.Mvc.SelectListItem> Events { get; set; }
public Telerik.Web.Mvc.GridModel<CustomerEventRolesModel> GridData { get; set; }
}
public class CustomerEventRolesModel : BaseNopEntityModel
{
public string Customer { get; set; }
public bool Sponsor { get; set; }
public bool Speaker { get; set; }
}
My .cshtml
<table id="grdCustomerEventRoleData" class="adminContent" style="display: none">
<tr>
<td>
<p>
</p>
</td>
</tr>
<tr>
<td>
#(Html.Telerik().Grid<CustomerEventRolesModel>(Model.GridData.Data)
.Name("grdCustomerEventRoles")
.Columns(columns =>
{
columns.Bound(x => x.Customer);
columns.Bound(x => x.Speaker).Template(x => Html.CheckBox("spk", x.Speaker));
columns.Bound(x => x.Sponsor).Template(x => Html.CheckBox("spn", x.Sponsor));
}
) .Pageable(settings => settings.Total(Model.GridData.Total)
.PageSize(gridPageSize)
.Position(GridPagerPosition.Both))
.ClientEvents(events => events.OnDataBinding("onDataBinding"))
.DataBinding(dataBinding => dataBinding.Ajax().Select("FilterByDropdown", "Customer"))
.EnableCustomBinding(true))
) )
</td>
</tr>
<script type="text/javascript">
var initialLoad = true;
$("#select-event").change(function () {
if ($("#select-event option:selected").val() > 0) {
$("#grdCustomerEventRoleData").show();
$("#grdCustomerEventRoles").data("tGrid").rebind();
}
else {
$("#grdCustomerEventRoleData").show();
}
});
function onDataBinding(e) {
if (initialLoad == true) {
e.preventDefault();
initialLoad = false;
}
else {
var classificationId = $("#select-event option:selected").val();
if (classificationId != "")
e.data = $.extend(e.data, {
selEvent: classificationId
});
else {
e.preventDefault();
$("#grdCustomerEventRoleData").hide();
}
}
}
Actions in controller
public ActionResult FirstBind()
{
if (!_permissionService.Authorize(StandardPermissionProvider.ManageCustomers))
return AccessDeniedView();
var model = new CustomerEventRolesModels();
model.Event = 0;
List<Nop.Core.Domain.Catalog.Product> products = _productRepository.Table.Where(p => p.EventDate != null && p.EventDate >= DateTime.Now).ToList();
model.Events = products.Select(p => new System.Web.Mvc.SelectListItem
{
Text = p.Name,
Value = p.Id.ToString()
});
var grdmodel = new GridModel<CustomerEventRolesModel>
{
Data = null,
Total = 0
};
model.GridData = grdmodel;
return View(model);
}
[HttpPost, GridAction(EnableCustomBinding = true)]
public ActionResult FilterByDropdown(GridCommand command, int selEvent)
{
if (!_permissionService.Authorize(StandardPermissionProvider.ManageCustomers))
return AccessDeniedView();
if (selEvent == 0)
return View();
var model = new CustomerEventRolesModels();
model.Event = selEvent;
var roles = (from lst in _customerEventRoleRepository.Table
join cust in _customerRepository.Table on lst.CustomerId equals cust.Id
join product in _productRepository.Table on lst.EventId equals product.Id
join role in _customerRoleRepository.Table on lst.RoleId equals role.Id
orderby lst.Id descending
select new CustomerEventRolesModel
{
Id = lst.Id,
Customer = cust.Email,
Sponsor = (role.Name == "Sponsor") ? true : false,
Speaker = (role.Name == "Speaker") ? true : false
}).ToList();
var grdmodel = new GridModel<CustomerEventRolesModel>
{
Data = roles,
Total = roles.Count
};
model.GridData = grdmodel;
return new JsonResult
{
Data = model
};
}
FilterByDropdown action is works correctly but Grid is not binded.
I am clueless.
Please help.
If you want to add a dropdown to a Telerik MVC Grid when editing a row, you will need to follow next few steps (aside from making the grid ajax bound and the rows editable).
Let’s say we want the column representing a name (“Name” from the model) to be a dropdown, from which a name can be selected rather than typed. Add a folder named “EditorTemplates” to the folder containing the view that the grid is on. It will contain a separate partial view for each dropdown we want to show in the row that is being edited. Make a partial view (mentioned above), name it e.g. “ClientName.cshtml”, containing a Telerik DropDownList named “Name” and bound to required list of names.
#(Html.Telerik().DropDownList()
.Name("Name")
.BindTo(new SelectList((IEnumerable)ViewData["CustomerNames"], "Text", "Value"))
)
Add the following attribute to the “Name” property of the data type that the grid uses e.g. Grid uses “Customer” class, containing “string Name” field:
public class Customer{ [UIHint("ClientName"), Required] public string Name { get; set; } }
The UIHint property specifies which field template to use when a specific column is rendered.
Add the following java script to the page containing the grid function:
function onEditCustomerList(e) { if (e.dataItem != null) { $(e.form).find('#Name').data('tDropDownList').select(function (dataItem) { return dataItem.Text == e.dataItem['Name']; });
} }
This should do the trick.
You're returning the wrong model.
Try this in FilterByDropdown:
var grdmodel = new GridModel<CustomerEventRolesModel>
{
Data = roles,
Total = roles.Count
};
return new JsonResult
{
Data = grdmodel
};

url.Action with MvcContrib generates invalid links

In our application we use MvcContrib for generating links with the exception of cross area links where Contrib seems to be not working properly (or we are doing something wrong). In services we have a function that generates a List< ZakladkaModel > which contains url and other properties used in generating tabstrib via custom html helper. That function takes as an argument an id of database object and UrlHelper to help in link creating.
m_service.GenerowanieZakladkiDlaKontrolera_ARCH_Akt(idAktu, new UrlHelper(this.ControllerContext.RequestContext));
Then in the GenerowanieZakladkiDlaKontrolera_ARCH_Akt we have something like this:
model.Add(new ZakladkaModel { Aktywnosc = true, NazwaZakladki = "Akt", Url = "" });
model.Add(new ZakladkaModel { Aktywnosc = true, NazwaZakladki = "Wzmianki", Url = url.Action<Usc.Presentation.Areas.FU_RAU.Controllers.ARCH.ARCH_WzmiankiController>(c => c.Index(idAktu)) });
if (tekstJednolity.StanTekstuJednolitego == "RB" || tekstJednolity.StanTekstuJednolitego == "SW")
{
model.Add(new ZakladkaModel { Aktywnosc = true, NazwaZakladki = "t.j. aktu", Url = url.Action<Usc.Presentation.Areas.FU_RAU.Controllers.ARCH.ARCH_TekstJednolityController>(c => c.Edytuj(tekstJednolity.Id)) });
}
else
{
model.Add(new ZakladkaModel { Aktywnosc = true, NazwaZakladki = "t.j. aktu", Url = url.Action<Usc.Presentation.Areas.FU_RAU.Controllers.ARCH.ARCH_TekstJednolityController>(c => c.Raport(tekstJednolity.Id)) });
}
model.Add(new ZakladkaModel { Aktywnosc = true, NazwaZakladki = "Przypisek 1", Url = url.Action<Usc.Presentation.Areas.FU_RAU.Controllers.ARCH.Przypisek1Controller>(c => c.Index(idAktu)) });
model.Add(new ZakladkaModel { Aktywnosc = true, NazwaZakladki = "Przypisek 2", Url = url.Action<Usc.Presentation.Areas.FU_RAU.Controllers.ARCH.Przypisek2Controller>(c => c.Index(idAktu)) });
model.Add(new ZakladkaModel { Aktywnosc = true, NazwaZakladki = "Przypisek 3", Url = url.Action<Usc.Presentation.Areas.FU_RAU.Controllers.ARCH.Przypisek3Controller>(c => c.Edytuj(idAktu)) });
model.Add(new ZakladkaModel { Aktywnosc = true, NazwaZakladki = "Przypisek 4", Url = url.Action<Usc.Presentation.Areas.FU_RAU.Controllers.ARCH.Przypisek4Controller>(c => c.Edytuj(idAktu)) });
Now the problem is that on some co-workers computers it generates links to actions properly and on some it looks like it takes a ranedom area from our app and tries to make an invalid link. We could use a simple url.Action("action","controler") which works fine on all but we would prefer MvcContrib :). Does anyone have any idea why this occurs? Or can share an alternative?
It seems that LinkBuilder which is used under doesn't use GetVirtualPatchForArea at all which as I read is MVC bug. So i decided to make my own HtmlHelper which uses that method:
public static string ActionArea<TController>(this HtmlHelper urlHelper, Expression<Action<TController>> expression) where TController : Controller
{
RouteValueDictionary routeValues = GetRouteValuesFromExpression(expression);
VirtualPathData vpd = new UrlHelper(urlHelper.ViewContext.RequestContext).RouteCollection.GetVirtualPathForArea(urlHelper.ViewContext.RequestContext, routeValues);
return (vpd == null) ? null : vpd.VirtualPath;
}
public static string ActionArea<TController>(this UrlHelper urlHelper, Expression<Action<TController>> expression) where TController : Controller
{
RouteValueDictionary routeValues = GetRouteValuesFromExpression(expression);
VirtualPathData vpd = urlHelper.RouteCollection.GetVirtualPathForArea(urlHelper.RequestContext, routeValues);
return (vpd == null) ? null : vpd.VirtualPath;
}
public static RouteValueDictionary GetRouteValuesFromExpression<TController>(Expression<Action<TController>> action) where TController : Controller
{
if (action == null)
{
throw new ArgumentNullException("action");
}
MethodCallExpression call = action.Body as MethodCallExpression;
if (call == null)
{
throw new ArgumentException("Akcja nie może być pusta.", "action");
}
string controllerName = typeof(TController).Name;
if (!controllerName.EndsWith("Controller", StringComparison.OrdinalIgnoreCase))
{
throw new ArgumentException("Docelowa klasa nie jest kontrolerem.(Nie kończy się na 'Controller')", "action");
}
controllerName = controllerName.Substring(0, controllerName.Length - "Controller".Length);
if (controllerName.Length == 0)
{
throw new ArgumentException("Nie można przejść do kontrolera.", "action");
}
// TODO: How do we know that this method is even web callable?
// For now, we just let the call itself throw an exception.
string actionName = GetTargetActionName(call.Method);
var rvd = new RouteValueDictionary();
rvd.Add("Controller", controllerName);
rvd.Add("Action", actionName);
var namespaceNazwa = typeof(TController).Namespace;
if(namespaceNazwa.Contains("Areas."))
{
int index = namespaceNazwa.IndexOf('.',namespaceNazwa.IndexOf("Areas."));
string nazwaArea = namespaceNazwa.Substring(namespaceNazwa.IndexOf("Areas.") + 6, index - namespaceNazwa.IndexOf("Areas.") + 1);
if (!String.IsNullOrEmpty(nazwaArea))
{
rvd.Add("Area", nazwaArea);
}
}
//var typ = typeof(TController).GetCustomAttributes(typeof(ActionLinkAreaAttribute), true /* inherit */).FirstOrDefault();
/*ActionLinkAreaAttribute areaAttr = typ as ActionLinkAreaAttribute;
if (areaAttr != null)
{
string areaName = areaAttr.Area;
rvd.Add("Area", areaName);
}*/
AddParameterValuesFromExpressionToDictionary(rvd, call);
return rvd;
}
private static string GetTargetActionName(MethodInfo methodInfo)
{
string methodName = methodInfo.Name;
// do we know this not to be an action?
if (methodInfo.IsDefined(typeof(NonActionAttribute), true /* inherit */))
{
throw new InvalidOperationException(String.Format(CultureInfo.CurrentUICulture,
"Nie można wywoływać metod innych niż akcje.", methodName));
}
// has this been renamed?
ActionNameAttribute nameAttr = methodInfo.GetCustomAttributes(typeof(ActionNameAttribute), true /* inherit */).OfType<ActionNameAttribute>().FirstOrDefault();
if (nameAttr != null)
{
return nameAttr.Name;
}
// targeting an async action?
if (methodInfo.DeclaringType.IsSubclassOf(typeof(AsyncController)))
{
if (methodName.EndsWith("Async", StringComparison.OrdinalIgnoreCase))
{
return methodName.Substring(0, methodName.Length - "Async".Length);
}
if (methodName.EndsWith("Completed", StringComparison.OrdinalIgnoreCase))
{
throw new InvalidOperationException(String.Format(CultureInfo.CurrentUICulture,
"Nie można wywoływać kompletnych metod.", methodName));
}
}
// fallback
return methodName;
}
static void AddParameterValuesFromExpressionToDictionary(RouteValueDictionary rvd, MethodCallExpression call)
{
ParameterInfo[] parameters = call.Method.GetParameters();
if (parameters.Length > 0)
{
for (int i = 0; i < parameters.Length; i++)
{
Expression arg = call.Arguments[i];
object value = null;
ConstantExpression ce = arg as ConstantExpression;
if (ce != null)
{
// If argument is a constant expression, just get the value
value = ce.Value;
}
else
{
value = CachedExpressionCompiler.Evaluate(arg);
}
rvd.Add(parameters[i].Name, value);
}
}
}
Hope this helps people with similiar problems. Some of the code above i got from mvc2-rtm-sources modified to my needs http://aspnet.codeplex.com/releases/view/41742

MVC 3 RAZOR - how to use hidden fields to maintain state of checkboxes between page request?

I am using Hidden fields to maintain the state of my checkboxes between page requests except it doesn't work. So when I click on my webgrid to go to the next 15 records it forgets which checkboxes are checked.
Index view
#model IEnumerable<UserManager.Models.vw_UserManager_Model>
#{
ViewBag.Title = "User Manager Dashboard";
}
#Html.ActionLink("Create New User", "CreateUser")
#using (#Html.BeginForm())
{
<div class="webgrid-filter">
#{Html.RenderAction("_WebGridFilter", "UserManager");}
</div>
<div id="webgrid-wrapper">
#Html.Partial("~/Views/Partial/_WebGridUserManager.cshtml", Model)
</div>
<br />
}
<script type="text/javascript">
$(document).ready(function () {
// Disable checkboxs where a user is not active.
$(".webgrid-wrapper input:not(:checked)").attr("disabled", "disabled");
// Style tables.
function jQueryUIStyling() {
$('input:button, input:submit').button();
$('.webgrid-wrapper').addClass('ui-grid ui-widget ui-widget-content ui-corner-all');
$('.webgrid-title').addClass('ui-grid-header ui-widget-header ui-corner-top');
jQueryTableStyling();
} // end of jQueryUIStyling
function jQueryTableStyling() {
$('.webgrid').addClass('ui-grid-content ui-widget-content');
$('.webgrid-header').addClass('ui-state-default');
$('.webgrid-footer').addClass('ui-grid-footer ui-widget-header ui-corner-bottom ui-helper-clearfix');
} // end of jQueryTableStyling
});
</script>
<script type="text/javascript">
function filterGrid() {
var filters = getFilterVals();
$.ajax({
url: '#Url.Action("Index", "UserManager")',
type: "POST",
async: true,
dataType: "html",
data: "alfConnect=" + filters.alfConnect + "&" + "alfIntelligence=" + filters.alfIntelligence + "&" + "brad=" + filters.brad,
success: function (data) {
$('#webgrid-wrapper').empty().html(data);
// $('#webgrid-wrapper').html(data);
}
});
}
function getFilterVals() {
filters = new Object();
if ($('.webgrid-filter #chkFilterAlfIntell').is(':checked')) {
filters.alfIntelligence = 1;
}
else {
filters.alfIntelligence = 0;
}
if ($('.webgrid-filter #chkFilterAlfConn').is(':checked')) {
filters.alfConnect = 1;
}
else {
filters.alfConnect = 0;
}
if ($('.webgrid-filter #chkFilterBrad').is(':checked')) {
filters.brad = 1;
}
else {
filters.brad = 0;
}
return filters;
}
function logUserOff(url) {
var answer = confirm('Are you sure you want to save this data?')
if (answer) {
// alert(url + ": " + value);
$.ajax({
url: url,
type: "POST"
// data: value
}).done(function () {
$(this).addClass("done");
});
return true;
}
else {
return false;
}
};
</script>
Partial view with hidden fields
#model UserManager.Models.webgrid_validation
<b>#Html.Label("Select a filter: ")</b>
<br />
#Html.Label("Toggle ALF Intelligence users:")
#Html.CheckBoxFor(model => model.chkBoxAlfIntelligence, new
{
id = "chkFilterAlfIntell",
onclick = "filterGrid()",
#checked = "checked"
})
#Html.Hidden("hdnAlfIntelligence", Model.chkBoxAlfIntelligence)
#Html.Label("Toggle ALF Connect users:")
#Html.CheckBoxFor(model => model.chkBoxAlfConnect, new
{
id = "chkFilterAlfConn",
onclick = "filterGrid()",
#checked = "checked"
})
#Html.Hidden("hdnAlfConnect", Model.chkBoxAlfConnect)
#Html.Label("Toggle BRAD users:")
#Html.CheckBoxFor(model => model.chkBoxBrad, new
{
id = "chkFilterBrad",
onclick = "filterGrid()",
#checked = "checked"
})
#Html.Hidden("hdnBrad", Model.chkBoxBrad)
Controller
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using UserManager.Models;
namespace UserManager.Controllers
{
public class UserManagerController : Controller
{
//
// GET: /UserManager/
public ActionResult Index()
{
try
{
var model = new UserManagerTestEntities().vw_UserManager_Model;
return View(model.ToList());
}
catch (Exception ex)
{
return View(ViewBag);
}
}
[HttpPost]
public ActionResult Index(int alfConnect, int alfIntelligence, int brad)
{
List<UserManager.Models.vw_UserManager_Model> modelList = DAL.getGrid(alfConnect, alfIntelligence, brad);
switch (alfConnect)
{
case 1:
ViewData["chkBoxAlfConnect"] = 1;
break;
case 0:
ViewData["chkBoxAlfConnect"] = 0;
break;
}
switch (alfIntelligence)
{
case 1:
ViewData["chkBoxAlfIntelligence"] = 1;
break;
case 0:
ViewData["chkBoxAlfIntelligence"] = 0;
break;
}
switch (brad)
{
case 1:
ViewData["chkBoxBrad"] = 1;
break;
case 0:
ViewData["chkBoxBrad"] = 0;
break;
}
return PartialView("~/Views/Partial/_WebGridUserManager.cshtml", modelList);
}
[ChildActionOnly]
public ActionResult _WebGridFilter ()
{
UserManager.Models.webgrid_validation model = new webgrid_validation();
return PartialView("~/Views/Partial/_WebGridFilter.cshtml", model);
}
//public ActionResult _WebGridFilter(int alfConnect, int alfIntelligence, int brad)
//{
// UserManager.Models.webgrid_validation model = new webgrid_validation();
//switch (alfConnect)
//{
// case 1:
// model.chkBoxAlfConnect = true;
// break;
// case 0:
// model.chkBoxAlfConnect = false;
// break;
//}
//switch (alfIntelligence)
//{
// case 1:
// model.chkBoxAlfIntelligence = true;
// break;
// case 0:
// model.chkBoxAlfIntelligence = false;
// break;
//}
//switch (brad)
//{
// case 1:
// model.chkBoxBrad = true;
// break;
// case 0:
// model.chkBoxBrad = false;
// break;
//}
// return PartialView("~/Views/Partial/_WebGridFilter.cshtml", model);
//}
#region ajaxMethods
public ActionResult LookUpGroupName(string q, int limit)
{
try
{
//TODO: Map list to autocomplete textbox control
DAL d = new DAL();
List<string> groups = d.groups();
var GroupValue = groups
.Where(x => x.Contains(q))
.OrderBy(x => x)
.Take(limit)
.Select(r => new { group = r });
// Return the result set as JSON
return Json(GroupValue, JsonRequestBehavior.AllowGet);
}
catch (Exception ex)
{
return View(ex.ToString());
}
}
public ActionResult LogUserOff(string userid)
{
try
{
//TODO: Map list to autocomplete textbox control
return View();
}
catch (Exception ex)
{
return View(ex.ToString());
}
}
//[HttpPost]
//public ActionResult FilterGrid(int alfConnect, int alfIntelligence, int brad)
//{
// List<UserManager.Models.vw_UserManager_Model> modelList = DAL.getGrid(alfConnect, alfIntelligence, brad);
// return PartialView("_WebGridUserManager", modelList);
//}
#endregion
#region crud
public ActionResult CreateUser()
{
//var data = new UserManager.Models.UserManagerTestEntities();
ViewBag.Message = "Create New User";
var model = new vw_UserManager_Model();
return View(model);
}
[HttpPost]
public ActionResult CreateUser (vw_UserManager_Model model)
{
int outcome = 0;
if (ModelState.IsValid)
{
//var data = new UserManager.Models.UserManagerTestEntities();
// Pass model to Data Layer
outcome = UserManager.DAL.CreateUser(model, outcome);
//data.SaveChanges();
}
if (outcome > 0) // Success
{
return RedirectToAction("showSuccess", model);
}
else // Failure
{
return RedirectToAction("showError", new { ErrorMessage = "Error" });
}
}
public ActionResult EditUser(Guid userid, string salutation, string firstname, string lastname, string password, Nullable<bool> isactive, Nullable<int> maxconcurrentusers, string email, string module, string group)
{
vw_UserManager_Model editUser = new vw_UserManager_Model();
editUser.userid = userid;
editUser.salutation = salutation;
editUser.firstname = firstname;
editUser.lastname = lastname;
editUser.password = password;
editUser.isactive = isactive;
editUser.MaxConcurrentUsers = maxconcurrentusers;
editUser.email = email;
editUser.module_name = module;
editUser.group_name = group;
return View(editUser);
}
[HttpPost]
public ActionResult EditUser(vw_UserManager_Model editUser)
{
if (ModelState.IsValid)
{
UserManager.DAL.EditUser(editUser);
}
return View();
}
public ActionResult DeleteUser(Guid userid, string username, string salutation, string firstname, string lastname, string password, bool isactive, string email, string module, string group)
{
vw_UserManager_Model DeleteUser = new vw_UserManager_Model();
DeleteUser.userid = userid;
DeleteUser.UserName = username;
DeleteUser.salutation = salutation;
DeleteUser.firstname = firstname;
DeleteUser.lastname = lastname;
DeleteUser.password = password;
DeleteUser.isactive = isactive;
DeleteUser.email = email;
DeleteUser.module_name = module;
DeleteUser.group_name = group;
return View(DeleteUser);
}
[HttpPost]
public ActionResult DeleteUser(vw_UserManager_Model deleteUser)
{
if (ModelState.IsValid)
{
UserManager.DAL.DeleteUser(deleteUser);
return RedirectToAction("showSuccess", new { SuccessMessage = "Success" });
}
return View();
}
#endregion crud
#region successErrorHandling
public ActionResult showError(List<string> ErrorMessage)
{
ViewBag.ErrorMessage = ErrorMessage[0];
return View("ErrorMessageView");
}
public ActionResult showSuccess(vw_UserManager_Model model)
{
return View("SuccessMessageeView", model);
}
#endregion
}
}
My question is how to use hidden fields to maintain state of checkboxes between page request?
you could remove the form and send data to the controller as JSon values, and thus refresh only the part of the page that needs to be refreshed.
Regards

Ajax Request in MVC3

I am new to Ajax, I am trying to fetch data from database with an ajax call using jquery.
I have a list of country tabs and I am trying to display data when there is an user action
Here is my code sample, at the moment it is saying there is a null system reference.
public ActionResult Details(int id, string searchTerm)
{
// Do we have a search term
if (!String.IsNullOrEmpty(searchTerm))
{
// decode the searchTerm as we dont want to search for encoded bits
searchTerm = Decode(searchTerm);
}
var a = _mRepository.GetMyId(id);
if (a == null)
{
return View("NotFound");
}
// Here we need to get list of countries for the selected manufacturer
var c = _mwRepository.Getcountries(id);
ViewData["Countries"] = c.ToArray();
// Now we need list of products for the manufacturer countries and this is an Ajax call to database so that it fetches data only when there is a user action
foreach (var country in c)
{
var p = _productRepository.GetAllCurrentProductsForManufacturerCountry(id,
country.Id);
}
if(Request.IsAjaxRequest())
{
ViewData["ManufacturerCountryProducts"] =
p.ToArray();
}
public class CountryProducts
{
public Country Country { get; set; }
public List<Product> ProductsList { get; set; }
}
[HttpPost]
public ActionResult Details( int id, string searchTerm )
{
// Do we have a search term
if ( !String.IsNullOrEmpty( searchTerm ) )
{
// decode the searchTerm as we dont want to search for encoded bits
searchTerm = Decode( searchTerm );
}
var a = _mRepository.GetMyId( id );
if ( a == null )
{
return View( "NotFound" );
}
// Here we need to get list of countries for the selected manufacturer
List<Country> countriesList = _mwRepository.Getcountries( id );
var data = new List<CountryProducts>();
if ( countriesList != null )
{
foreach (var country in countriesList)
{
List<Product> products = _productRepository.GetAllCurrentProductsForManufacturerCountry(id,
country.Id);
data.Add(new CountryProducts() {Country = country, ProductsList = products});
}
}
if (Request.IsAjaxRequest())
{
ViewData["CountryProducts"] = data.ToArray();
}
}
But i'm use two different methods for ajax, such as:
public ActionResult Details( int id )
{
...
return View(model);
}
//for ajax request:
[HttpGet]
public JsonResult Details( int id, string searchTerm )
{
return new JsonResult()
{
JsonRequestBehavior = JsonRequestBehavior.AllowGet,
Data = GetFilteredDetailsData(id, searchTerm)
};
}

Set current, before current and after current elements in menu

For setting that I use Html helper method which is not the best imo, because I use static field.
public enum CurrentState
{
BeforeCurrent,
AfterCurrent
}
public static CurrentState currentState = CurrentState.BeforeCurrent;
public static MvcHtmlString ActiveActionLink(this HtmlHelper helper, string linkText, string actionName, string controllerName, bool checkAction = true)
{
string currentAction = helper.ViewContext.RouteData.GetRequiredString("action");
string currentController = helper.ViewContext.RouteData.GetRequiredString("controller");
if ((controllerName == currentController) && checkAction && (actionName == "Index"))
{
currentState = CurrentState.BeforeCurrent;
}
if ((controllerName == currentController) && checkAction && (actionName != currentAction))
{
if (currentState == CurrentState.BeforeCurrent)
{
return helper.ActionLink(linkText, actionName, controllerName, null, new { #class = "beforeCurrent" });
}
else if (currentState == CurrentState.AfterCurrent)
{
return helper.ActionLink(linkText, actionName, controllerName, null, new { #class = "afterCurrent" });
}
}
if ((controllerName == currentController) && (!checkAction || (actionName == currentAction)))
{
currentState = CurrentState.AfterCurrent;
return helper.ActionLink(linkText, actionName, controllerName, null, new { #class = "current" });
}
return helper.ActionLink(linkText, actionName, controllerName);
}
I have two levels of menus and that's why I use checkAction parameter:
main menu - #Html.ActiveActionLink(Resources.Global.mainMenuBoard, "Index", "Board", checkAction: false)
side menu - #Html.ActiveActionLink(#Resources.Global.managementOverview, "Index", "Management")
and in side menu I need to know if it's after and before current (overlapping items...).
Is it a way to improve that?
Additionally I must say that I use javascript also for that but it must work also for javascript disabled.
I finally solve that by generating whole menu in one helper:
public class Link
{
public string LinkText { get; set; }
public string ActionName { get; set; }
}
public static List<MvcHtmlString> SubMenuLinks(this HtmlHelper helper, string controllerName, List<Link> links)
{
List<MvcHtmlString> menuElements = new List<MvcHtmlString>();
string actualCssClass = "beforeCurrent";
string currentAction = helper.ViewContext.RouteData.GetRequiredString("action");
string currentController = helper.ViewContext.RouteData.GetRequiredString("controller");
foreach (Link link in links)
{
if (controllerName == currentController && link.ActionName == currentAction)
{
menuElements.Add(helper.ActionLink(link.LinkText, link.ActionName, controllerName, null, new { #class = "current" }));
actualCssClass = "afterCurrent";
}
else
{
menuElements.Add(helper.ActionLink(link.LinkText, link.ActionName, controllerName, null, new { #class = actualCssClass }));
}
}
return menuElements;
}
and in view:
#{
List<MvcHtmlString> actionMenu = Html.SubMenuLinks("Manager", new List<Link>()
{
new Link() { LinkText = "linkText", ActionName = "actionName" },
new Link() { LinkText = "linkText2", ActionName = "actionName2" }
});
}
#section SideMenu
{
#for (int i = 0; i < actionMenu.Count; i++)
{
<li id="menu#(i)">#actionMenu.ElementAt(i)</li>
}
}
Not perfect, but it works at least.

Resources