Display data on logged user MVC4 - asp.net-mvc

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.

Related

model does not contain a public instance definition for 'OnlineUserModel'

On my View:
#model IEnumerable<Project.Models.OnlineUserModel>
<div class="form-group online">
<ul>
#foreach (var user in Model)
{
<li>
#Html.DisplayFor(modelItem => user.UserName) <br />
</li>
}
</ul>
</div>
AJAX:
$(function () {
$.ajax({
type: "POST",
url: "/Home/OnlineUsers",
MODEL :
public class OnlineUserModel
{
public string UserName { get; set; }
public string UserID { get; set; }
public OnlineUserModel(DataRow rs)
{
if (!DBNull.Value.Equals(rs["UserName"])) this.UserName = (string)rs["UserName"];
if (!DBNull.Value.Equals(rs["UserID"])) this.UserID = (string)rs["UserID"];
}
public static List<OnlineUserModel> OnlineUsersList()
{
List <OnlineUserModel> user = new List<OnlineUserModel>();
DataTable resultTable = Globals.CommonData.RetrieveOnlineUsers();
if (resultTable != null)
{
foreach (DataRow rs in resultTable.Rows)
{
user.Add(new OnlineUserModel(rs));
}
}
return user;
}
}
CONTROLLER:
[HttpPost]
public JsonResult OnlineUsers()
{
return Json(Project.Models.OnlineUserModel.OnlineUsersList());
}
I did the same exact way on my other project and it is working fine but this one keeps giving me error and I need help in figuring it out. Probably an obvious one for the experienced contributor here but not for me. Thank you, Pls point me to the right direction.

how to pass checkbox value to controller on form submit then return data to view?

In My view i placed a check box in-front of some user records .when I check a check box and click on submit button then the selected checkbox values (user Id) will be sent to controller. currently i successfully get emails in my model but can't get the DB result back in view.
Customers View :
#using (Html.BeginForm())
{
<table class="table table-responsive">
#foreach (var s in Model)
{
<td id="list"><input type="checkbox" name="ids" id="ids" value="#s.Id" /></td>
}
<tr>
<td><button class="btn btn-primary" id="sendmail" type="submit">Send Email To Customers</button></td>
</tr>
</table>
}
#if (TempData["Emails"] != null)
{
<span class="alert-info">#TempData["Emails"]</span>
}
Controller :
[HttpPost]
public ActionResult Customers(int[] ids)
{
Customers cu= new Customers();
cu.IDS = ids;
cu.GetEmails(ids);
TempData["ids"] = string.Join(",", ids.ToArray());
TempData["Emails"] = cu.GetEmails(ids).Email.ToArray(); // I want these emails in my view
return RedirectToAction("Customers");
}
Model :
public Customers GetEmails(int[] ids)
{
Customers ee = new Customers();
SqlConnection con = new SqlConnection(ConfigurationManager.ConnectionStrings["mvc"].ConnectionString);
string qry = "select Email from users where Id IN(" + string.Join(",", ids.ToArray()) + ")";
SqlCommand cmdd = new SqlCommand(qry, con);
con.Open();
SqlDataReader rdd = cmdd.ExecuteReader();
while (rdd.Read())
{
ee.Email = rdd["Email"].ToString(); // I am able to get all emails
}
rdd.Close();
cmdd.ExecuteNonQuery();
con.Close();
return ee;
}
Well lets start with some dummy data and test case scenario
public ActionResult Test()
{
return View();
}
[HttpPost]
public ActionResult Test(MyModel model)
{
TempData["test"] = GetData();
return View();
}
public List<string> GetData() //method for get data
{
List<string> mylist = new List<string>(new string[] { "element1", "element2", "element3" });
return mylist;
}
and razor view
var data = TempData["test"] as List<string>;
if (data != null)
{
foreach (var a in data)
{
W‌riteLiteral(#"<li>"); /*​*/
W‌rite(a); /*​*/
W‌riteLiteral(#"</li>");
}
}
Now with your scenario I assume that your GetEmail only return a set of string so change your return type to Customer object to list<string> as public List<string> GetEmails() and return ee as list of string.
Then all you need to do in your razor view like test case scenario.

Combining Create and Index Views in one View in Asp.Net MVC 5

I have a controller in my Dashboard Area and an action to return categories as a list to view and another action to create new category
My Actions:
public ActionResult Categories() {
return View(db.Categories.OrderBy(Categories => Categories.Name).ToList());
}
[HttpPost]
public RedirectToRouteResult NewCategory(string name, string address, string parentId) {
if (ModelState.IsValid) {
int? ParentID = null;
if (parentId != "null") {
ParentID = parentId.AsInt();
}
Category oCategory = new Category();
oCategory.Name = name;
oCategory.Address = address;
oCategory.ParentID = ParentID;
db.Categories.Add(oCategory);
db.SaveChanges();
db.Dispose();
db = null;
}
return RedirectToAction("Categories");
}
I have a pure HTML form inside the Categories View to get user inputs to create a new category and a block that represents the categories that I already have.
I have a Select and several Foreach loops that iterates through categories from parent to children inside my form.
Here is the code:
<select name="parentID" id="parentCategoryId">
<option value="null" selected>nothing</option>
#foreach (var Category in Model) {
if (Category.ParentID == null) {
<option value="#Category.ID">#Category.Name</option>
foreach (var SubCategory1 in Model) {
if (SubCategory1.ParentID == Category.ID) {
<option value="#SubCategory1.ID">
»
#SubCategory1.Name
</option>
foreach (var SubCategory2 in Model) {
if (SubCategory2.ParentID == SubCategory1.ID) {
<option value="#SubCategory2.ID">
»
#SubCategory2.Name
</option>
foreach (var SubCategory3 in Model) {
if (SubCategory3.ParentID == SubCategory2.ID) {
<option value="#SubCategory3.ID">
»
#SubCategory3.Name
</option>
}
}
}
}
}
}
}
}
</select>
Inside the view I get the data from Model using :
#model IEnumerable<project.Models.Category>
But I need another Model object to use here:
#Html.ValidationMessageFor(model => model.Title, "", new { #class = "text-danger" })
and validation operation!
The question is how can I combine these two views?
And now I’m stuck with this error:
Validation failed for one or more entities. See 'EntityValidationErrors' property for more details.
You need create model:
public class CategoryModel {
public string Name {get;set;}
public string Address {get;set;}
pubic string ParentId {get;set;}
public IEnumerable<Category> Categories {get;set;}
}
In your Controller:
public ActionResult Categories() {
var model = new CategoryModel();
model.Categories = db.Categories.OrderBy(Categories => Categories.Name).ToList();
return View(model);
}
[HttpPost]
public RedirectToRouteResult NewCategory(CategoryModel model) {
if (ModelState.IsValid) {
int? ParentID = null;
if (model.ParentId != "null") {
ParentID = model.ParentId.AsInt();
}
Category oCategory = new Category();
oCategory.Name = Model.Name;
oCategory.Address = Model.Address;
oCategory.ParentID = ParentID;
db.Categories.Add(oCategory);
db.SaveChanges();
db.Dispose();
db = null;
}
return RedirectToAction("Categories");
}
and in the view:
#model project.Models.CategoryModel
now you can create fields like in the same view:
#Html.EditorFor(Model=>model.Title)
#Html.ValidationMessageFor(model => model.Title, "", new { #class = "text-danger" })

ASP.NET MVC 3 Dropdownlist of Users

In my application I have associated my UserId to a table in my database. I need that when I create a new item I can choose the user name from a dropdownlist. And 'possible to do this with the element viewbag?
#Html.EditorFor(model => model.UserId)
I use default membership provider so I can't use Entity Framework for this problem
EDIT
EDIT 2
This is my action create:
[HttpPost]
public ActionResult Create(Employe employe)
{
var users = Roles.GetUsersInRole("Admin");
SelectList list = new SelectList(users);
ViewBag.Users = list;
if (ModelState.IsValid)
{
**employe.EmployeID = users;**
db.Employes.Add(employe);
db.SaveChanges();
}
This does not work. The error is:
Cannot implicitly convert type 'string[]' to 'string'
My model for Employee
public class Employee
{
[Key]
public int EmployeID { get; set; }
public Guid UserId { get; set; }
public string Name { get; set; }
[ForeignKey("UserId")]
public virtual MembershipUser User
{
get
{
return Membership.GetUser(this.Name); //Changed this to Name
}
}
}
}
View:
#Html.DropDownList("Users", ViewBag.Users as SelectList);
My result in UserId field isn't a UserId but this 000000-000000-0000000-00000
How to set a list of users as a SelectItem in the ViewBack
Yes, you should be able to do this by passing your collection to the ViewBag and then create you dropdown from it:
In your controller
var users = Roles.GetUsersInRole("Admin");
SelectList list = new SelectList(users);
ViewBag.Users = list;
In your View (If you're using Razor)
#Html.DropDownList("Users", ViewBag.Users as SelectList);
Read more about SelectListItem here:
http://msdn.microsoft.com/en-us/library/system.web.mvc.selectlistitem.aspx
Also check out:
How can I get this ASP.NET MVC SelectList to work?
Problem with ASP.Net MVC SelectLIst and List<SelectListItems>
Question changed to something more. Here is my idea to solve the issue:
Controller:
public ActionResult Mirko() {
List<SelectListItem> items = new List<SelectListItem>();
foreach (string userName in Roles.GetUsersInRole("Admin")) {
var user = Membership.GetUser(userName);
SelectListItem li = new SelectListItem {
Value = user.ProviderUserKey.ToString(),
Text = user.UserName,
};
items.Add(li);
}
items.Add(new SelectListItem { Text = "Please Select...", Value = "na" , Selected = true});
ViewBag.Users = items;
return View();
}
[HttpPost]
public ActionResult Mirko(Employee employee) {
if(IsValideEmployee(employee)) {
/*Only used to show that user was retrieved*/
TempData["message"] = "Saved Employee";
TempData["user"] = employee.User;
/* employeeRepository.Save(employee) */
/* Redirect to where you want to go */
return RedirectToAction("Mirko", "Home");
}
return View(employee);
}
private bool IsValideEmployee(Employee emp) {
if (emp.Name == "na")
ModelState.AddModelError("UserId", "You must select a user!");
/*Do some validation here*/
//ModelState.Add("Name", "You must set the user name!")
return ModelState.IsValid;
}
View
#model StackOverFlowExample.Models.Employee
#{
MembershipUser user = null;
ViewBag.Title = "Mirko Example";
var users = ViewBag.Users as IEnumerable<SelectListItem>;
}
#if (TempData["message"] != null) {
user = TempData["user"] as MembershipUser;
<h3>#TempData["message"]</h3>
<div>
<span>You selected #user.UserName</span>
<ul>
<li>Email: #user.Email</li>
<li>Last Logged In: #user.LastLoginDate.ToString("d")</li>
<li>Online: #user.IsOnline</li>
</ul>
</div>
}
#using (#Html.BeginForm()) {
<label for="UserId">Associate Employee To User:</label>
#Html.DropDownListFor(m => m.UserId, #users)
#Html.HiddenFor(m => m.Name)
<input type="submit" value="Save" id="save-employee"/>
}
<div id="status" style="display:none;"></div>
<script type="text/javascript">
$(document).ready(function () {
$("#UserId").change(function () {
//Set value of name
$("#Name").val($(this).children("option:selected").text());
});
$("#save-employee").click(function (e) {
var value = $("#Name").val();
if (value == "" || value == "na") {
e.preventDefault();
$("#status").html("<h3>You must select a user!</h3>").toggle();
}
});
});
</script>

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