I using MvcSiteMapProvider to create treeview navigator in Asp.net MVC 4
I have 2 link like:
~/Home/Article/{id} and
~/Home/Gallery/{id}
my Treeview like: Home -> Article -> Gallery
And I used dynamic code on Controller
[MvcSiteMapNode(Title = "Article", ParentKey = "Home", Key="Article", PreservedRouteParameters="id")]
public ActionResult Article(int id)
{
ViewBag.Id = id;
return View();
}
[MvcSiteMapNode(Title = "Gallery", Key="Gallery" ParentKey = "Article", PreservedRouteParameters="id")]
public ActionResult Gallery(int id)
{
ViewBag.id = id;
return View();
}
So it run success, but Problem is when i have
~/Home/Article/123 and I go to ~/Home/Gallery/456
Next I click on treeview to go back Article, it set wrong ID parameter in article, It get Gallery's id set for Article's Id look like: ~/Home/Article/456.
Anyone have solver?. Sorry about my english, it bad.
You could explicitly set the name of the parameter.
Eg.
[MvcSiteMapNode(Title = "Article", ParentKey = "Home", Key="Article", PreservedRouteParameters="ArticleId")]
public ActionResult Article(int ArticleId)
{
ViewBag.Id = ArticleId;
return View();
}
[MvcSiteMapNode(Title = "Gallery", Key="Gallery" ParentKey = "Article", PreservedRouteParameters="GalleryId")]
public ActionResult Gallery(int GalleryId)
{
ViewBag.id = GalleryId;
return View();
}
Then:
/Home/Article/123
/Home/Gallery?GalleryId=456&ArticleId=123
Related
How can i display data in views in asp.net core MVC?. In the Index.cshtml I have the following link to the detail page.
#Html.ActionLink("You_Controller_Name", "GetProductsDetail", new { id = item.ID }) |
I have this controller to get product by ID
public IActionResult Detail()
{
return View();
}
[HttpGet()]
public async Task<IActionResult> GetProductsDetail(string id)
{
var product_list = (await ProductService.GetProducts()).ToList();
var product = product_list.FirstOrDefault(a => a.ProductCode == id);
return view(product);
}
Need help on displaying Product information in the detail page.
You could also pass the ProductName to Detail action using RedirectToAction,and then display it on view using ViewBag.
Controller:
[HttpGet]
public async Task<IActionResult> GetProductsDetail(string id)
{
var product_list = (await ProductService.GetProducts()).ToList();
var product = product_list.FirstOrDefault(a => a.ProductCode == id);
return RedirectToAction("Detail", new { name = product.ProductName });
}
public IActionResult Detail(string name)
{
ViewBag.ProductName = name;
return View();
}
Detail View:
<h1>#ViewBag.ProductName</h1>
You should do this in GetProductsDetail Action
return View("Detail", product);
Read the following to have a better understanding
Updated
You can store like this in
#ViewBag.ProductName = product.ProductName
In View:
<h1>#ViewBag.ProductName</h1>
Full code
[HttpGet]
public async Task<IActionResult> GetProductsDetail(string id)
{
var product_list = (await ProductService.GetProducts()).ToList();
var product = product_list.FirstOrDefault(a => a.ProductCode == id);
#ViewBag.ProductName = product.ProductName
return View("Detail", product); // Make sure that in View is expecting `ProductList`, Otherwise, You just return View("Detail");
}
Calling another different view from the controller using ASP.NET MVC 4
I want to add posts to threads in my forum project, but to do so I need to pass a parameter with thread ID, so after creating post it will redirect me back to that specific thread, but the problem is that I have no idea how to pass that parameter...
Here is my Create() code:
// GET: /Posts/Create
public ActionResult Create(int id)
{
ViewBag.ThreadId = new SelectList(db.Albums, "ThreadId", "Title");
ViewBag.IdOfThread = id;
return View();
}
//
// POST: /Posts/Create
[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult Create(Posts posts)
{
if (ModelState.IsValid)
{
db.Posts.Add(posts);
db.SaveChanges();
return RedirectToAction("Index", new { **id = 5** });
}
ViewBag.ThreadId = new SelectList(db.Albums, "ThreadId", "Title", posts.ThreadId);
//ViewBag.IdOfThread = id;
return View(posts);
}
When I strongly type number id = 5 it works as intended, so how can I make ActionResult Create(Posts posts) see my ViewBoxes from Create View? Or maybe there is some better way to do that without using ViewBoxes?
Through the glory of EF when you add a model to the Entity and call SaveChanges() it will automatically put the ID back into the model.
if (ModelState.IsValid)
{
db.Posts.Add(posts);
db.SaveChanges();
// Replace Id with whatever your auto increment PK is.
return RedirectToAction("Index", new { id = posts.Id });
}
This question should be very simple.. I am trying to pass values in my drop down list in my view to the controller.. I'm not getting errors but it's sending a null value for that property. Please help..
My code is as follows:
Controller:
public ActionResult Create()
{
var list = new []
{
new Room{ RoomID = 1, Building = "FAYARD HALL"},
new Room{ RoomID = 2, Building = "WHATEVER HALL"},
new Room{ RoomID = 3, Building = "TIME SQUARE"},
new Room{ RoomID = 4, Building = "MISSISSIPPI"},
new Room{ RoomID = 5, Building = "NEW YORK"},
};
var selectList = new SelectList(list,"RoomID", "Building");
ViewData["BuildingList"] = selectList;
return View();
}
//
// POST: /Room/Create
[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult Create(Room room)
{
if (ModelState.IsValid)
{
db.Rooms.Add(room);
db.SaveChanges();
return RedirectToAction("Index");
}
return View(room);
}
MY VIEW:
<div>
#Html.LabelFor(model => model.Building, "Building")
</div>
<div>
#Html.DropDownList("BuildingList", String.Empty)
#Html.ValidationMessageFor(model => model.Building)
</div>
Please help...
Thank you.
Is your drop down populated? Given your code I think you need the following to do so:
#Html.DropDownListFor(model => model.Building, ViewData["BuildingList"])
ie. bind the selected value to the Building property of your Room and use the drop down list from your view model to populate the list.
I'm also not sure this is what your intention is. It seems a bit fishy that you are populating a drop down list with rooms and then based on the selection you are creating a new room.
Edit
Ok I'm going to make things a lot easier for you.
I'll start with your classes. Here is the room I am assuming you're working with:
public class Room
{
public int RoomId { get; set; }
public string Building { get; set; }
}
Now let's do something a bit better than using ViewData. I've created a view model for you. You will populate this with your select list and the item you choose in the view will be bound into the SelectedRoomId when you post the form.
public class ViewModel
{
public int SelectedRoomId { get; set; }
public SelectList RoomOptions { get; set; }
}
Controller
private SelectList GetSelectList()
{
var list = new[]
{
new Room { RoomId = 1, Building = "FAYARD HALL"},
new Room { RoomId = 2, Building = "WHATEVER HALL"},
new Room { RoomId = 3, Building = "TIME SQUARE"},
new Room { RoomId = 4, Building = "MISSISSIPPI"},
new Room { RoomId = 5, Building = "NEW YORK"}
};
return new SelectList(list, "RoomId", "Building");
}
public ActionResult Create()
{
ViewModel viewModel = new ViewModel
{
RoomOptions = GetSelectList()
};
return View(viewModel);
}
[HttpPost]
public ActionResult Create(ViewModel viewModel)
{
if (ModelState.IsValid)
{
// Save here
// create a new room using the SelectedOptionId in the viewModel
return RedirectToAction("Index", "Home");
}
// repopulate the list if something failed
viewModel.RoomOptions = GetSelectList();
return View(viewModel);
}
View
#model PathToYourViewModel.ViewModel
#using (Html.BeginForm())
{
#Html.DropDownListFor(model => model.SelectedRoomId, Model.RoomOptions, "-- select an option --")
<button type="submit">Submit</button>
};
Tried and tested. Good luck!
The model binding takes place with help of the names property in mvc .
In your case the name of your control is BuildingList:
#Html.DropDownList("BuildingList", (SelectList)ViewData["BuildingList"])
Therefore at your controller Action will go as follows:
[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult Create(FormCollection collection)
{
var selectedValue = collection["BuildingList"];
}
i am trying to create a stackoverflow like url.
I the following example works fine. But if i remove the controller then it errors out.
http://localhost:12719/Thread/Thread/500/slug-url-text
Note the first Thread is the controller the second is the action.
How can i make the above URL look like the following excluding the controller name from the url?
http://localhost:12719/Thread/500/slug-url-text
My Routes
public class RouteConfig
{
public static void RegisterRoutes(RouteCollection routes)
{
routes.IgnoreRoute("{resource}.axd/{*pathInfo}");
routes.MapRoute("Default", // Route name
"{controller}/{action}/{id}/{ignoreThisBit}",
new
{
controller = "Home",
action = "Index",
id = "",
ignoreThisBit = ""
}); // Parameter defaults )
}
}
Thread Controller
public class ThreadController : Controller
{
//
// GET: /Thread/
public ActionResult Index()
{
string s = URLFriendly("slug-url-text");
string url = "Thread/" + 500 + "/" + s;
return RedirectPermanent(url);
}
public ActionResult Thread(int id, string slug)
{
return View("Index");
}
}
Placing the following route before the default route definition will directly call the 'Thread' action in 'Thread' controller with the 'id' and 'slug' parameter.
routes.MapRoute(
name: "Thread",
url: "Thread/{id}/{slug}",
defaults: new { controller = "Thread", action = "Thread", slug = UrlParameter.Optional },
constraints: new { id = #"\d+" }
);
Then if you really want it to be like stackoverflow, and assume someone enters the id part and not the slug part,
public ActionResult Thread(int id, string slug)
{
if(string.IsNullOrEmpty(slug)){
slug = //Get the slug value from db with the given id
return RedirectToRoute("Thread", new {id = id, slug = slug});
}
return View();
}
hope this helps.
#Html.ActionLink("LotNumberDetails", "Index", "LotNumber", new { id = item.lotNUmber }, null)
This is my action link in table, when I click on LotNumber ActionLink it generates the following URL:
http://servername.com/LotNumber/Index/1111_100868781211
The method in controller is as follows:
[HttpGet]
public ActionResult Index(string id)
{
var TupleResult = objLotNumberModel.GetLotNumberValuesEnumerable(id);
return View("Index", TupleResult);
}
Everything is working fine, but when I change ActionLink to Ajax.ActionLink...
#Ajax.ActionLink("LotNumber", "Index", "LotNumber", new { id = item.lotNUmber }, new AjaxOptions { HttpMethod = "POST"})
and the controller method to...
[HttpPost]
public ActionResult Index(string id)
{
var TupleResult = objLotNumberModel.GetLotNumberValuesEnumerable(id);
return View("Index", TupleResult);
}
The method is firing but I can't move to respective page.
My idea is to hide the ID of LotNumber, ie when clicking on ActionLink I Just want to get the URL like "http://servername.com/LotNumber/Index".