Passing parameters from model to controller in razor application - c#

I have a problem in my asp.net mvc4 application :
i'am passing two integers as a parameteres to an action :
<a>#Html.ActionLink(s, "Gerer_Sequence", "Travail", new { seq = Model[k][i].Id_séquence , affa = aff.Id_affaire } )</a>
the action is :
public ActionResult Gerer_Sequence(int seq, int affa)
{
Session["affaire"] = affa;
Session["sequence"] = seq;
return RedirectToAction("Index", "Calendar");
}
the problem is that the parameters are null however the its values are 3 and 1 in the model.
So what is the problem? How can i modify my code to fix the error?

Try this.
<td>
#Html.ActionLink("EditUser", "Index", new { Id = m.ID,Name = m.Name })
</td>
public ActionResult Index(string Id, string Name)
{
var model = new RegisterModel();
int _ID = 0;
int.TryParse(Id, out _ID);
if (_ID > 0)
{
RegisterModel register = GetRegisterUserById(_ID);
model.ID = _ID;
model.Name = register.Name;
model.Address = register.Address;
model.PhoneNo = register.PhoneNo;
}
return View(model);
}

You just need to change this:
new { seq = Model[k][i].Id_séquence , affa = aff.Id_affaire }
to this:
new RouteValueDictionary { { "seq", Model[k][i].Id_séquence }, { "affa", aff.Id_affaire } }
because the fourth parameter you're using is the route values.

Try this:
#Html.ActionLink(s, "Gerer_Sequence", "Travail", new { seq = Model[k][i].Id_séquence , affa = aff.Id_affaire }, null )

Remove the tag
Ensure that parameters you have provided are int values.
After that run your application and check the link generated, if values are ok then it should be ok.

i put the action in the same controller:
#Html.ActionLink("Gerer Sequence", "Gerer_Sequence", new { seq = Model[k][i].Id_séquence , affa = aff.Id_affaire } )

Related

Making a default in a DropDownListFor when displaying from a model

How can I make a blank default to be displayed like " " in this #Html.DropDownListFor.
I have tried the over-rides and they don't work for this.
HTML:
<td>#Html.DropDownListFor(o => o.TerminalsDDL, Model.TerminalsDDL, new { id = "ddlTerminalID", #class = "form-control align-middle" })</td>
Controller:
public ActionResult Index()
{
var model = TCBL.GetTerminalData();
return View(model);
}
//POST: TerminalCommand/Index
/*This function will insert a user selecter terminal command into the TerminalCommand table*/
public ActionResult AddTerminalCommand(AddTerminalCommandVM input)
{
TerminalCommand terminalCommand = new TerminalCommand();
terminalCommand.TerminalID = input.TerminalID;
terminalCommand.Command = input.CommandID;
terminalCommand.CommandValue = input.CommandValue;
TCBL.AddTerminalCommand(terminalCommand);
var redirectUrl = new UrlHelper(Request.RequestContext).Action("Index", "TerminalCommand");
return Json(new { Url = redirectUrl });
}
Data Layer:
/*Gets All termianls for the terminalsDDL and all terminal Cmds for Model.TerminalCommands*/
public TerminalCommandVM GetTerminalData()
{
TerminalCommandVM terminals = new TerminalCommandVM();
//For Terminal drop downs
terminals.TerminalsDDL = TCDA.GetTerminalsDropDown();
//For terminal cmd lists
terminals.TerminalCommands = TCDA.GetAll();
//For helpdescription
terminals.HelpDescriptions = TCDA.GetAllHelpDescriptionValues();
terminals.HelpDescriptionID = TCDA.GetAllHelpDescriptionIDs();
//For TerminalCommandLookupsDDL
List<SelectListItem> terminalCommandLookups = new List<SelectListItem>();
var terminalCommandLookupsResults = TCDA.GetAllTerminalCommandLookups().OrderBy(o => o.Name); //.Where(x => x.Name.Contains("S3"));
if (terminalCommandLookupsResults != null)
{
foreach (var item in terminalCommandLookupsResults)
{
SelectListItem newItem = new SelectListItem();
newItem.Text = item.Name;
newItem.Value = item.ID.ToString();
terminalCommandLookups.Add(newItem);
}
}
var terminalCommandValues = TCDA.GetAllTerminalCommandValues();
terminals.TerminalCommandValues = terminalCommandValues;
terminals.TerminalCommandLookupsDDL = terminalCommandLookups;
return terminals;
}
Bottom is data access layer, where the CA gets the data for display. I believe HTML should have some sort of default blank selection though..
You can add a blank default before the for loop in your Data Layer
SelectListItem newItem = new SelectListItem();
newItem.Text = "";
newItem.Value = "";
terminalCommandLookups.Add(newItem);
you can use this overload of Dropdownlistfor -
Html.DropDownListFor(Expression<Func<dynamic,TProperty>> expression, IEnumerable<SelectLestItem> selectList, string optionLabel, object htmlAttributes)
like this
<td>#Html.DropDownListFor(o => o.TerminalsDDL, Model.TerminalsDDL,"", new { id = "ddlTerminalID", #class = "form-control align-middle" })</td>

How does ctx.SaveChanges() affect return View("Action", model) vs return RedirectToAction("Action")

I have a controller with two actions. One action is simply a post that updates the database. The other is the view model. However in my action that updates the database I return it back to the original view with the view model.
public ActionResult ManageMxieUsers()
{
var model = from el in aphdb.view_EmployeeList
join p in aphdb.MxieCallRevPermissions on el.Id equals p.AspNetUserUserID into gj
from sub in gj.DefaultIfEmpty()
select new vm_ManageMxieUsers { Id = el.Id, UserName = el.UserName, PermissionLevel = sub.PermissionLevel, MxieCallRevPermCustomList = aphdb.MxieCallRevPermCustomList.Where(w => w.PermissionID == sub.PermissionID ) };
ViewBag.EmployeeList = aphdb.view_EmployeeList.OrderBy(o => o.UserName);
return View(model);
}
This part works perfectly.
Here is my post method:
[HttpPost]
public ActionResult ManageMxieUsers(string userID, Int16 permissionLevel, List<string> customUserList)
{
var UserToEdit = aphdb.MxieCallRevPermissions.Where(w => w.AspNetUserUserID == userID).FirstOrDefault();
if (UserToEdit == null)
{
MxieCallRevPermissions addPerm = new MxieCallRevPermissions();
addPerm.AspNetUserUserID = userID;
addPerm.PermissionLevel = permissionLevel;
aphdb.MxieCallRevPermissions.Add(addPerm);
aphdb.SaveChanges();
if (permissionLevel == 3)
{
foreach (var id in customUserList)
{
MxieCallRevPermCustomList list = new MxieCallRevPermCustomList();
list.PermissionID = addPerm.PermissionID;
list.AspNetUserID = id;
aphdb.MxieCallRevPermCustomList.Add(list);
}
}
aphdb.SaveChanges();
#ViewBag.Success = true;
}
else
{
UserToEdit.PermissionLevel = permissionLevel;
aphdb.SaveChanges();
if (permissionLevel == 3)
{
// Remove old custom list
var customList = aphdb.MxieCallRevPermCustomList.Where(w => w.PermissionID == UserToEdit.PermissionID).ToList();
aphdb.MxieCallRevPermCustomList.RemoveRange(customList);
aphdb.SaveChanges();
foreach (var id in customUserList)
{
MxieCallRevPermCustomList list = new MxieCallRevPermCustomList();
list.PermissionID = UserToEdit.PermissionID;
list.AspNetUserID = id;
aphdb.MxieCallRevPermCustomList.Add(list);
}
aphdb.SaveChanges();
}
else
{
// Remove old custom list
var customList = aphdb.MxieCallRevPermCustomList.Where(w => w.PermissionID == UserToEdit.PermissionID).ToList();
aphdb.MxieCallRevPermCustomList.RemoveRange(customList);
aphdb.SaveChanges();
}
aphdb.SaveChanges();
#ViewBag.Success = true;
}
//aphdb.SaveChangesAsync(); // Testing ot make sure SaveChanges fired before this code.
var model = from el in aphdb.view_EmployeeList
join p in aphdb.MxieCallRevPermissions on el.Id equals p.AspNetUserUserID into gj
from sub in gj.DefaultIfEmpty()
select new vm_ManageMxieUsers { Id = el.Id, UserName = el.UserName, PermissionLevel = sub.PermissionLevel, MxieCallRevPermCustomList = aphdb.MxieCallRevPermCustomList.Where(w => w.PermissionID == sub.PermissionID) };
ViewBag.EmployeeList = aphdb.view_EmployeeList.OrderBy(o => o.UserName);
//return RedirectToAction("ManageMxieUsers"); // WORKS
return View("ManageMxieUsers", model); // ERROR NULL on AspNetUser
}
Now when I simply return View("ManageMxieUsers", model); The error comes back saying AspNetUsers is null. However when I reload this page it works just fine. When I return RedirectToAction("ManageMxieUsers"); I get no error, but of course I lose my ViewBag.
My only guess is that aphdb.SaveChanges() is not reflected instantly? Even tho I can perform a SQL query to the database and see the data has indeed been added/updated. As is referenced by reloading the current page.
So I'm at a loss as to why during this post method my view model portion comes up with null entries, but when I reload it they are populated normally.
I'm fine with leaving it as RedirectToAction, but would like to maybe understand better as to why this behavior is making it work.
Here is the view portion that breaks
<tbody>
#{ int? permissionLevel; }
#foreach (var user in Model)
{
permissionLevel = user.PermissionLevel ?? 4;
<tr>
<td>#user.Id</td>
<td>
#user.UserName
</td>
<td>#permissionLevel</td>
<td>
#foreach (var customUser in user.MxieCallRevPermCustomList)
{
#("[" + customUser.AspNetUsers.FirstName + " " + customUser.AspNetUsers.Lastname + "] ")
}
</td>
</tr>
}
</tbody>
the customUser.AspNetUsers = null when I use return View("ManageMxieUsers", model); in my [HttpPost] method.

MVCjqDrid store GridSettings in session

I have a mvcjqgrid:
#(Html.Grid("dataGrid")
.SetJsonReader(new MvcJqGrid.DataReaders.JsonReader { Id = "Id", RepeatItems = false })
.SetRequestType(RequestType.Post)
.AddColumn(new Column("Name").SetLabel("Name").SetSearch(true))
.AddColumn(new Column("Email").SetLabel("E-Mail").SetSearch(true).SetFormatter(Formatters.Email))
.AddColumn(new Column("Phone").SetLabel("Phone").SetSearch(true))
.SetSearchToolbar(true)
.SetUrl(Url.Action("GetData", "Controller"))
.SetSearchOnEnter(false)
.SetRowNum(10)
.SetRowList(new[] { 10, 15, 20, 50 })
.SetViewRecords(true)
.SetPager("pager"))
and controller:
public ActionResult GetData()
{
return View(new myEntity[0]);
}
[HttpPost]
public JsonResult GetData(GridSettings gridSettings)
{
int totalRecords = DataHelper.GetCount();
var data = DataHelper.GetData(gridSettings);
var jsonData = new
{
total = totalRecords / gridSettings.PageSize + 1,
page = gridSettings.PageIndex,
records = totalRecords,
rows = data
};
return Json(jsonData);
}
EDIT:
so my question is how can i store GridSettings in session in right way, i need every time user backs to this page, page should be the same as when he left?
If i do:
Session["settings"] = gridSettings;
i need some way to compare stored gridSettings with the one passed to action.
Why don't you use the Http Cache for this case? We can write a caching provider, and Http Cache is one implementation for this. So in the future you can extend more providers for it.
The answer is to recreate Grid:
#{
var setting = Session["settings"] as GridSettings;
}
#(Html.Grid("dataGrid")
.SetJsonReader(new MvcJqGrid.DataReaders.JsonReader { Id = "Id", RepeatItems = false })
.SetRequestType(RequestType.Post)
.AddColumn(new Column("Name").SetLabel("Name").SetSearch(true))
.AddColumn(new Column("Email").SetLabel("E-Mail").SetSearch(true).SetFormatter(Formatters.Email))
.AddColumn(new Column("Phone").SetLabel("Phone").SetSearch(true))
.SetSearchToolbar(true)
.SetUrl(Url.Action("GetData", "Controller"))
.SetSearchOnEnter(false)
.SetRowNum(setting != null?setting.PageSize : 10)
.SetPage(setting != null?setting.PageIndex : 1);
.SetSortName(setting != null?setting.SortColumn : "");
.SetRowList(new[] { 10, 15, 20, 50 })
.SetViewRecords(true)
.SetPager("pager"))

How to set the static text into JsonResult?

I found the following code example (from Telerik ) that I'm trying to understand.
What I need to do is somehow to set static text into JsonResult (e.g.Text ="Abc" and Value="123")
public ActionResult _AjaxLoading(string text)
{
Thread.Sleep(1000);
using ( var nw = new NorthwindDataContext() )
{
var products = nw.Products.AsQueryable();
if ( text.HasValue() )
{
products = products.Where((p) => p.ProductName.StartsWith(text));
}
return new JsonResult { Data = new SelectList(products.ToList(), "ProductID", "ProductName") };
}
}
public ActionResult _AjaxLoading(string text
{
var data = new { Text= "123", Value= "Abc"};
return Json(data, JsonRequestBehavior.AllowGet);
}
If it is an HTTPGet method, You should specify JsonRequestBehavior.AllowGet as second parameter to return JSon data from a GET method
It looks like you are in need of this:
return new JsonResult { Data = new { Text="Abc", Value="123", Produtcs= new SelectList(products.ToList(), "ProductID", "ProductName") }};
Is this what you are looking for
return new JsonResult { Text = "Abc", Value="123" };
If you want to add a new element to the drop down at start then
var editedProducts = new SelectList(products.ToList(), "ProductID","ProductName" ).ToList();
editedProducts.insert(0, new SelectListItem() { Value = "123", Text = "Abc" });
return new JsonResult { Data = editedProducts };

Change Devexpress export row value

My Controller:
public ActionResult ExportTo(ExportFormat exportFormat = ExportFormat.Xlsx)
{
ExportType exportType = GridViewHelper.ExportTypes.SingleOrDefault(x => x.Format == exportFormat);
if (exportType != null)
{
var modelList= modelRepository.GetAll();
var gridviewSettings = CreateExportGridViewSettings();
if(gridviewSettings != null)
return exportType.Method(gridviewSettings, modelList);
}
return RedirectToAction("Index");
}
...
private GridViewSettings CreateExportGridViewSettings()
{
var settings = new GridViewSettings
{
Name = "Export",
CallbackRouteValues = new {Controller = "MyController", Action = "List"},
Width = Unit.Percentage(100)
};
settings.Columns.Add("Id", Resources.Id);
!!! ---- !!!
...
}
!!! ---- !!! <- Here I want to add column. the row output in this column must be YES if value is True and NO if value is False
settings.Columns.Add(set =>
{
set.FieldName = "IsSomething";
set.Caption = "Is Something";
set.UnboundType = DevExpress.Data.UnboundColumnType.String;
set.UnboundExpression = "Iif([IsSomething]==True, 'Yes', 'No')";
});

Categories

Resources