Can't pass parameter id in actionLink - asp.net-mvc-3

Can't understand where the problem... My rout values is :
routes.MapRoute(
"Default", // Route name
"{controller}/{action}/{id}", // URL with parameters
new { controller = "Home", action = "Index", id = UrlParameter.Optional } // Parameter defaults
);
And i try to pass parameter id :
#Html.ActionLink(app.Name, "SingleAppEdit", "Admin", new { id = app.Id }, null)
To my action in Controller "Admin":
public ActionResult SingleAppEdit(string appId)
{
var positions = new List<SelectListItem>
{
new SelectListItem() {Text = "Top", Value = "Top"},
new SelectListItem() {Text = "Bottom", Value = "Bottom"},
new SelectListItem() {Text = "None", Value = "None"}
};
ViewData["PositionsList"] = new SelectList(positions, "Value", "Text");
var app = Apps.FirstOrDefault(a => a.Id == Convert.ToInt32(appId));
return View(app);
}
I get null in controller. Can anybody help?

Your method parameter name is appId. But you are trying to pass a parameter named id.
Solution : Change your parameter name to match with the method definition.
#Html.ActionLink(app.Name, "SingleAppEdit", "Admin",
new { appId= app.Id }, null)

Change appID in controller to just ID like this:
public ActionResult SingleAppEdit(string id)
{
var positions = new List<SelectListItem>
{
new SelectListItem() {Text = "Top", Value = "Top"},
new SelectListItem() {Text = "Bottom", Value = "Bottom"},
new SelectListItem() {Text = "None", Value = "None"}
};
ViewData["PositionsList"] = new SelectList(positions, "Value", "Text");
var app = Apps.FirstOrDefault(a => a.Id == Convert.ToInt32(id));
return View(app);
}

Related

MVC ListBox Selected Values

New to MVC and Stackoverflow so sorry for not having enough reputation to post images...
Trying to render a ListBox with pre selected values
My SQL Database:
http://i.imgur.com/bcdXyqE.png
My Entity Framework
http://i.imgur.com/wYWXuAq.png
My Controller
public ActionResult AccessRights(int id)
{
var user = db.User.Find(id);
var roles = db.Role;
var newList = new List<SelectListItem>();
foreach (var role in roles)
{
newList.Add(
new SelectListItem()
{
Value = role.Id.ToString(),
Text = role.RoleName,
Selected = user.Role.Contains(role)
}
);
}
ViewBag.x = new SelectList(newList, "Value", "Text");
ViewBag.Roles = new SelectList(db.Role, "Id", "RoleName", user.Role);
return View(user);
}
My View
<p>try1:</p>
#Html.ListBox("Roles", null, new { #class = "form-control", #size = 6, #style = "height: initial" })
<p>try2:</p>
#Html.ListBox("x", null, new { #size = 6, #style = "height: initial" })
Non of the 2 tries renders with pre selected values?
got it working.
public ActionResult AccessRights(int id)
{
var user = db.User.Find(id);
IEnumerable<SelectListItem> roles = db.Role.Select(c => new SelectListItem{ Value = c.Id.ToString(), Text = c.RoleName, Selected = true});
var rolesSelected = new int[user.Role.Count];
var i = 0;
foreach (var role in user.Role)
{
rolesSelected[i] = role.Id;
i++;
}
ViewBag.Roles = roles.ToList();
ViewBag.RolesSelected = rolesSelected;
return View(user);
}
#Html.ListBox("RolesSelect", new MultiSelectList(ViewBag.Roles, "Value", "Text", ViewBag.RolesSelected), new { #class = "form-control", #size = 6, #style = "height: initial" })

How to Bind dropdown from anonymous class values

I want to populate a dropdown with values A,Band C.The below code works for create only,not for edit.
ViewBag.UserType = new[] { new SelectListItem { Text = "A", Value = "1", Selected = false }, new SelectListItem { Text = "B", Value = "2", Selected = false }, new SelectListItem { Text = "C", Value = "3", Selected = false } };
So I created an anonymous class. I have an anonymous class like below.
var Roles= new[]
{ new { Id =1,UserType="A" },
new {Id=2,UserType="B" },
new {Id=3,UserType="B" }
};
ViewBag.Type = Roles.ToList();
But i dont know how to fill dropdown in View.
#Html.DropDownListFor(model => model.UserType, ((IEnumerable<SelectListItem>)ViewBag.UserType).Select(option => new SelectListItem
{
Text = (option == null ? "None" : option.Text),
Value = option.Value.ToString(),
Selected = (Model != null) && (option.Value == (Model.UserType).ToString())
}),"Select")
What changes should i make in the view
Add following properties to your ViewModel class -
public SelectList Roles
{
get
{
List<SelectListItem> items = new List<SelectListItem>();
items.Add(new SelectListItem
{
Value = "1",
Text = "A",
});
items.Add(new SelectListItem
{
Value = "2",
Text = "B",
});
items.Add(new SelectListItem
{
Value = "3",
Text = "C",
});
return new SelectList(items, "Value", "Text");
}
}
public int SelectedRole { get; set; }
and bind in View as follows -
#Html.DropDownListFor(model => model.SelectedRole, Model.Roles)

How to use dropdownlistfor in mvc3 razor with model

I want to use below property in my view with dropdownbox.
How could I ?
I have tried so many ways but
Please help
public IEnumerable<SelectListItem> Topic
{
get
{
return new[]
{
new SelectListItem { Value = "1", Text = "Science", Selected=true },
new SelectListItem { Value = "2", Text = "History" },
new SelectListItem { Value = "3", Text = "Physics" },
};
}
}
You have not added your view code.
Basically you need to add a #model to your view like this:
#model MySampleApplication.Models.ModelName
And then in your view you should be accessing like this :
#Html.DropdownListFor(m=>m.Topic, Model.Topic)
DropDownListFor with ASP.NET MVC from Scott Allen
Hope it helps
EDIT
Say you have your model class like this:
public class MyModel
{
public IEnumerable<SelectListItem> Topic
{
get
{
return new[]
{
new SelectListItem { Value = "1", Text = "Science", Selected=true },
new SelectListItem { Value = "2", Text = "History" },
new SelectListItem { Value = "3", Text = "Physics" },
};
}
}
}
Try like this:
public ActionResult Index()
{
MyModel model=new MyModel();
return View(model);
}
Try this
Model
public SelectList Topic
{
get
{
return new SelectList(
new List<SelectListItem> {
new SelectListItem { Value = "1", Text = "Science", Selected = true },
new SelectListItem { Value = "2", Text = "History" },
new SelectListItem { Value = "3", Text = "Physics" }
},"Value","Text"
);
}
}
public int selectedType {get;set;}
View
#Html.DropDownListFor(model => model.selectedType , Model.Topic)

Avoid duplicate entries in List<SelectListItem>

How can I check that List< SelectListItem> doesn't contain or insert any duplicates in Mvc3. I have tried with !Contains
Thanks
Try this:
var list = new List<SelectListItem>();
list.Add(new SelectListItem { Text = "Some Text", Value = "Some Value" });
list.Add(new SelectListItem { Text = "Other Text", Value = "Other Value" });
var selectListItem = new SelectListItem { Text = "Some Text", Value = "Some Value" };
if(!list.Any(l => l.Value == selectListItem.Value)
{
list.Add(selectListItem);
}
.Contains() compares if the object reference, not the Value property
var list = new List<SelectListItem>();
var selectListItem = new SelectListItem { Text = "Some Text", Value = "Some Value" };
if(list.FirstOrDefault(t => t.Value != selectListItem.Value) == null)
{
list.Add(selectListItem);
}

MVC 2: Ajax.ActionLink redirect to new page when caller has MapRoute defined

everything works fine till I haven't defined route map for page having AJAX.
Controller
public ActionResult SessionDetails(int id, int collectionId, int sessionId) {
var model = new LegalActsListViewModel();
model.Setup(id, collectionId, sessionId, ApplicationContext.SessionService);
return PartialView("LegalActsListControl", model);
}
View
<%: Ajax.ActionLink(session.Name, "SessionDetails", "Institution", new { id = Model.InstitutionId, collectionId = Model.CollectionId, sessionId = session.Id }, new AjaxOptions { UpdateTargetId = "session_" + session.Id, OnSuccess = "updatePlaceholder", HttpMethod = "Post", InsertionMode = InsertionMode.Replace })%>
This above works perferct with default route map. In the moment I have added route map as below:
routes.MapRoute("Institution_Collection_Terms",
"institution/{id}/collection/{collectionId}/terms",
new { controller = "Institution", action = "Terms" },
new { id = #"\d+", collectionId = #"\d+" });
PartialResult is redirected to:
http://localhost:9085/Institution/SessionDetails/850?collectionId=22184&sessionId=77
Here are all routes:
routes.MapRoute("Institution_Collection_Keywords",
"institution/{id}/collection/{collectionId}/keywords",
new { controller = "Institution", action = "Keywords" },
new { id = #"\d+", collectionId = #"\d+" });
//routes.MapRoute("Institution_Collection_Terms",
// "institution/{id}/collection/{collectionId}/terms",
// new { controller = "Institution", action = "Terms" },
// new { id = #"\d+", collectionId = #"\d+" });
routes.MapRoute("Institution_Collection_Yearbooks",
"institution/{id}/collection/{collectionId}/yearbooks",
new { controller = "Institution", action = "Yearbooks" },
new { id = #"\d+", collectionId = #"\d+" });
routes.MapRoute("Institution_Collection_YearbookDetails",
"institution/{Id}/collection/{collectionId}/yearbook/{year}/{month}",
new { controller = "Institution", action = "YearbookList", month = UrlParameter.Optional },
new { Id = #"\d+", collectionId = #"\d+", year = #"^(19|20)\d{2}$" });
routes.MapRoute("Institution_Collection_List",
"institution/{id}/collection/{collectionId}/list",
new { controller = "Institution", action = "List" },
new { id = #"\d+", collectionId = #"\d+" });
routes.MapRoute("Institution_Collection_KeywordDetails",
"institution/{id}/collection/{collectionId}/keyword/{keywordId}",
new { controller = "Institution", action = "KeywordDetails" },
new { id = #"\d+", keywordId = #"\d+", collectionId = #"\d+" });
//routes.MapRoute("Institution_Collection_TermsDetails",
// "institution/{id}/collection/{collectionId}/session/{sessionId}/details",
// new { controller = "Institution", action = "SessionDetails" },
// new { id = #"\d+", sessionId = #"\d+", collectionId = #"\d+" });
routes.MapRoute("Institution_SearchLegalActs",
"institution/{institutionId}/searchlegalacts",
new { controller = "Institution", action = "SearchLegalActs" },
new { institutionId = #"\d+" });
routes.MapRoute("Institution_Keywords",
"institution/{id}/keywords",
new { controller = "Institution", action = "Keywords" },
new { id = #"\d+" });
routes.MapRoute("Institution_KeywordDetails",
"institution/{id}/keyword/{keywordId}",
new { controller = "Institution", action = "KeywordDetails" },
new { id = #"\d+", keywordId = #"\d+" });
routes.MapRoute("Institution_Yearbooks",
"institution/{id}/yearbooks",
new { controller = "Institution", action = "Yearbooks" },
new { id = #"\d+" });
routes.MapRoute("Institution_YearbookDetails",
"institution/{Id}/yearbook/{year}/{month}",
new { controller = "Institution", action = "YearbookList", month = UrlParameter.Optional },
new { Id = #"\d+", year = #"^(19|20)\d{2}$" });
routes.MapRoute("Institution_List",
"institution/{id}/list",
new { controller = "Institution", action = "List" },
new { id = #"\d+" });
routes.MapRoute("Institution_RecentAdded",
"institution/{id}/recentadded",
new { controller = "Institution", action = "RecentAdded" },
new { id = #"\d+" });
routes.MapRoute("Institution_MostPopular",
"institution/{id}/mostpopular",
new { controller = "Institution", action = "MostPopular" },
new { id = #"\d+" });
routes.MapRoute("Institution_Default",
"institution/{id}",
new { controller = "Institution", action = "Keywords" });
routes.MapRoute("Home_LegalActs",
"legalacts",
new { controller = "Home", action = "LegalActs" });
routes.MapRoute("Home_Institutions",
"institutions",
new { controller = "Home", action = "Institutions" });
routes.MapRoute("Home_Voivodeship",
"voivodeship/{voivodeship}",
new { controller = "Home", action = "Voivodeship" });
routes.MapRoute("Home_Journals",
"journals/{view}",
new { controller = "Home", action = "Journals" });
routes.MapRoute("Home",
"{controller}",
new { controller = "Home", action = "Index" });
routes.MapRoute("Default",
"{controller}/{action}/{id}",
new { controller = "Home", action = "Index", id = UrlParameter.Optional });
Thanks in advance,
Leszek

Resources