Getting null value instead of Id from View to Edit action method - asp.net-mvc

Getting 'null' from List View to Edit/Details/Delete Action method instead of the Id.
In List view, in Id column it shows corresponding Id without any issues. In All.cshtml file,
<td>
#Html.DisplayFor(modelItem => item.ModifiedOn)
</td>
<td>
#Html.ActionLink("Edit", "Edit", new { id = item.CategoryId }) |
#Html.ActionLink("Details", "Details", new { id = item.CategoryId }) |
#Html.ActionLink("Delete", "Delete", new { id = item.CategoryId })
</td>
And Edit method is,
public ActionResult Edit(int? id) {
if (id == null) {
return new HttpStatusCodeResult(HttpStatusCode.BadRequest);
return View();
}
var editCategory = new PetaPoco.Database("DefaultConnection");
var category = editCategory.Single<CategoryViewModels>("SELECT * FROM Category WHERE
CategoryId=#0 AND IsActive = 1", id);
return View(category);
}
The Url in the browser is, /Category/Edit/C1. But in Edit/Details/Delete, the Id is null.
What am I missing?
Thanks.

Since the url can be /Category/Edit/C1, the id parameter in the controller action method can't be an int?. Try to change the type of id to string
public ActionResult Edit(string id) {
if (string.IsNullOrEmpty(id)) {
return new HttpStatusCodeResult(HttpStatusCode.BadRequest);
return View();
}
var editCategory = new PetaPoco.Database("DefaultConnection");
var category = editCategory.Single<CategoryViewModels>("SELECT * FROM Category WHERE
CategoryId=#0 AND IsActive = 1", id);
return View(category);
}

the "C1" is not type of int, convert it to "int?" will get null.

Related

Pass an id and get it from actionLink to view page

I have this ActionLink into view named catalog
#Html.ActionLink("Formations", "Index", "Formation", new { id = item.Id },null)
and I want to get the list of formations of this catalog id.
How can I do this ?
In my database I have two tables :
Catalog:idC (PK),NameC,Date
Formation:idF(PK),idC(FK),NameF.
If your view's name is Catalog, you need to change your ActionLink to point to the corresponding action:
#Html.ActionLink("Formations", "Catalog", "Formation", new { id = item.Id }, null)
action:
public ActionResult Catalog(int id)
{
var formations = db.Formations.Where(f => f.idC == id).ToList;
return View(formations);
}
view:
#model IEnumerable<ProjectName.Models.Formation>
// loop your formations
#foreach (var item in Model)
{
// each formation iteration loops here
}

Display data on logged user MVC4

I have problem in displaying data of logged user. When i am logged i can go to other pages in my project, but when i need to list the categories of the logged user It is throwing an error:
The parameters dictionary contains a null entry for parameter 'userId' of non-nullable type 'System.Int32'
Here is my code:
Category Controller:
public ActionResult Index(int userId)
{
userId = WebSecurity.GetUserId(User.Identity.Name);
var categories = CategoryRepository.GetCategories(userId);
return View(categories);
}
SubCategory Controller:
public ActionResult SubCategory(int categoryId)
{
var subCategoies = SubCategoryRepository.GetSubCategories(categoryId);
return View(subCategoies);
}
Repository:
public static IEnumerable<Category> GetCategories(int userId)
{
try
{
var categories = (from cat in dc.Categories
where cat.UserId == userId
select cat).ToList();
return categories;
}
catch (Exception ex)
{
Utility.LogToTrace("CategoryRepository.GetCategories", ex.Message);
throw;
}
}
View:
#Html.ActionLink("Create Category","Create")
<br />
#Html.ActionLink("Create SubCategory", "Create", "SubCategory")
#foreach (var item in Model) {
<ul>
#Html.DisplayFor(model => item.Name)
<li>
#{ Html.RenderAction("SubCategory", "SubCategory", new {categoryId = item.Id}); }
</li>
</ul>
}
SubCategoryView:
#model IEnumerable<PasswordCloud.Domain.Models.SubCategory>
#foreach (var item in Model) {
#Html.ActionLink(item.Name,"Index", "Entry", new { subCategoryId = item.SubCategoryId }, null)
}
Any help abd suggestions what i am doing wrong.
Looking at the error , this is caused by this
#Html.ActionLink(item.Name,"Index", "Entry", new { subCategoryId = item.SubCategoryId }, null)
The link is set to go to "Index" action with "UserId" as parameter but you are passing the "SubcategoryID" which is causing this.
Change the name to Userid and Pass the Userid rather than the SubcategoryId.
Hope this helps.

How to use a dynamic var in ActionLink to call a different controller's action

Part of ControllerA:
public ActionResult Index()
{
ViewBag.Message = "ToolScope Testing";
var Baselines = from b in db.Baselines
orderby b.Name
select b;
ViewBag.Baselines = Baselines;
return View();
}
Part of View for ControllerA
#foreach (var item in #ViewBag.Baselines)
{
<tr>
<li> #Html.ActionLink( item.Name, "Details", "BaseLine",new { id = item.BaselineID }, null) </li>
</tr>
}
The item.Name is causing problem, however, it works if I use something like
<li> #Html.ActionLink( "SomeName", "Details", "BaseLine",new { id = item.BaselineID }, null) </li>
What should I do to have the dynamic names, i.e., the first ActionLink?
P.S.: I am new to MVC
I see you are new to MVC. Good news, you've already gotten the V(iew) and the C(ontroller). Now it's time to master the M(odel). In your example, you are using the ViewBag to transport knowledge from the Controller to your View. This is a typical responsibility of the Model. So you need to create a new class in your Models directory. It will probably look something like this:
public class MyFirstModel
{
public IEnumerable<MyCustomType> Baselines { get; set; }
public MyFirstModel() { }
}
Edit your Controller
public ActionResult Index()
{
ViewBag.Message = "ToolScope Testing";
var baselines = from b in db.Baselines
orderby b.Name
select b;
var model = new MyFirstModel
{
Baselines = baselines
};
return View(model);
}
Then, add this to the top of your View:
#model MvcApplication.Models.MyFirstModel
Now you can use this code in your view instead:
#foreach (var item in Model.BaseLines)
{
<tr>
<li> #Html.ActionLink( item.Name, "Details", "BaseLine",new { id = item.BaselineID }, null) </li>
</tr>
}

Details asp.net mvc4

I'm trying to open the details of the "Ansatte" object. The problem is that the Int parameter is only null
I have this View
#model IEnumerable<EL4.Administrasjon.Models.Ansatte>
<table>
#foreach (var item in Model) {
<tr data-pkey="#item.IdBaksystem">
<td>
#Html.DisplayFor(modelItem => item.AnsNavn)
</td>
<td>
#Html.DisplayFor(modelItem => item.ePostAdresse)
</td>
<td class="rowControl hidden">
#Html.ActionLink("Details", "Details", new { id=item.ID_Ansatt }) |
</td>
</tr>
}
Then I have this in the controller
public class HMAnsatteController : Controller
{
//
// GET: /HMAnsatte/
public ActionResult Index()
{
HM_000_EL4Entities hmEnt = new HM_000_EL4Entities();
List<Ansatte> HMansatte = hmEnt.Ansatte.ToList();
return View(HMansatte);
}
public ActionResult Details(int? ansattNr)
{
if (ansattNr == null)
{
return null;
}
else
{
Entities ent = new Entities();
Ansatt el4Ansatt = ent.Ansatt.Where(a => a.AnsattNr == ansattNr).First();
return View(el4Ansatt);
}
}
}
When I click details, the URL looks correct: http://localhost:50009/HMansatte/Details/1
But the int ansattNr is always "null"
you have this ...
public ActionResult Details(int? ansattNr)
and it should be this because of the dynamic object you are passing in the link
public ActionResult Details(int? id)
or change this instead ...
#Html.ActionLink("Details", "Details", new { ansattNr=item.ID_Ansatt })
It the line where you are creating your action link, you are naming the parameter "id" but in your action method, you are calling it "ansattNr". Those names should be the same. Since the default routing is already set up for "id", I would just change the method signature of your action method to this:
public ActionResult Details(int? id)
That should solve the problem.
Your passing an variable with a name of id into the controller (which your global.asax has mapped to the URL so it shows like it does) but your controller is looking for a variable with name ansattNr.
You can either change the name of the variable in your controller to id or you can change your Action link to #Html.ActionLink("Details", "Details", new { ansattNr=item.ID_Ansatt }) but the second option will change the formatting on your URL.

How do I display all user roles for users in my database?

I need to show all roles for users that are in my database. I'm using a LINQ query that I found on another SO posting. I'm having trouble with the snippet of code in my view and I'm getting this error: CS0103: The name 'AllUsers' does not exist in the current context. Here's my code...
ViewModel:
public class MyViewModel
{
public IEnumerable<MyUser> AllUsers { get; set; }
public List<MyUser> myList { get; set; }
}
Controller:
public class RoleController : Controller
{
public ActionResult GetUsers()
{
var roles = from MembershipUser u in Membership.GetAllUsers()
select new MyUser
{
User = u,
UserRoles = Roles.GetRolesForUser(u.UserName)
};
List<MyUser> res = new List<MyUser>();
foreach (MyUser u in roles)
res.Add(u);
MyViewModel model = new MyViewModel { AllUsers = res };
return View(model);
}
}
View (snippet):
<td>
#if(!(bool)(ViewBag.UserNameIsFound != null))
{
#Html.ActionLink("Add as user", "CreateUser", "Account")
<br />
foreach (MyUser u in Model.AllUsers)
{
foreach (string role in u.UserRoles)
{
AllUsers = MyList.Add(currItem);
Console.WriteLine(role + "<br />");
}
}
}
</td>
Any help would be greatly appreciated. Thanks in advance.
I think you need to change the following line of your view.
I don't know what is a variable named 'AllUsers' and why AllUsers is here?
AllUsers = MyList.Add(currItem);
I cannot get, what the 10th line means:
<td>
#if(!(bool)(ViewBag.UserNameIsFound != null))
{
#Html.ActionLink("Add as user", "CreateUser", "Account")
<br />
foreach (MyUser u in Model.AllUsers)
{
foreach (string role in u.UserRoles)
{
// what means the next line? what is "AllUsers"?
10: AllUsers = MyList.Add(currItem);
Console.WriteLine(role + "<br />");
}
}
}
</td>
What is AllUsers? I do not see it declared as a local variable.
If you mean Model.AllUsers, then you will iterate through the initial Model.AllUsers and will constantly change it to a new one. That is also not very clear.
Try to comment out the 10th line.

Resources