I am using asp.net MVC.
I have edit page url like {controller}/Edit/2
so on the view page how can I get the ID from this URL?
I'm gonna put a link to redirect to some page with sending above ID.
EDIT
Like
<%=Html.ActionLink("name", "Action", "Controller", new{ ID = ? } ) %>
you can get it from the RouteData object
<%=Html.ViewContext.RouteData.Values["id"].ToString() %>
Put the ID in the ViewData in your action method, then your view can access the value from the ViewData.
Controller: ViewData["ID"] = id;
View: <%=Html.ActionLink("name", "Action", "Controller", new{ ID = (int)ViewData["ID"]} ) %>
...in view you get info in the model to show data so you have id in model then you can get id and pass id easy
call Model in View :
#model IEnumerable<NewsWebsite.Models.Blog>
foreach (var item in Model)
{
//your code
#Html.ActionLink("Edit", "Edit", new { id = item.BlogID })
}
Or
you can get the id from URL Like This:
Cotroller:
public ActionResult Index(int id)
{
ViewBag.ID = id;
//Your Code......
return View(...);
}
View:
#{
ViewBag.Title = "Index";
var ID = ViewBag.ID;
}
Now you have an ID in the variable
I know of two ways: You can create your link and use the "ViewData" property to pass the link to your view or you can stronglyType the ViewPage.
Here is a link on strongly typing the view.
Related
I have a got a problem while passing parameters to the controller
Here is my view:
#model IEnumerable<WebApplication2.Models.Distributer>
#foreach (var item in Model) {
#Html.ActionLink("Edit", "Edit", new{id=item.DistributerID,user=item.Name })
}
My Controller
public ActionResult Edit(int? id,string name)
{
ViewBag.name = name;
}
In the Edit view just to display the name.
My RouteMap
routes.MapRoute(
name: "Route1",
url: "{controller}/{action}/{id}/{user}",
defaults: new { controller = "Distributers", action = "Edit", id = UrlParameter.Optional,user="" }
);
Here I find that variable name in the controller is null.Inorder to test the route works.I pull the link from the loop,ie;
#model WebApplication2.Models.Distributer
#Html.ActionLink("Edit", "Edit",new{id=item.DistributerID,user=Model.Name})
This works Fine..string name=value(not null)
Why is it so??
The parameter in your route and in your call to Html.ActionLink is user, but on your action method signature, it's name. In other words, user is being passed, but your action method does nothing with it. Conversely, the name parameter is never provided. Make sure that the parameter name lines up everywhere and you're golden.
I have a create action and a edit action in a Reviews Controller.
My Create ActionLink is:
#Html.ActionLink("Create New", "Create", new { Id = Model.Id })
My create action is :
[HttpGet]
public ActionResult Create(int Id)
{
return View();
}
My Edit ActionLink is:
#Html.ActionLink("Edit", "Edit", new { id=item.Id }
my edit is:
[HttpGet]
public ActionResult Edit(int id)
{
var model = _db.Reviews.Find(id);
return View(model);
}
In my edit view, I have a Action Link called "Back to List" which is:
#Html.ActionLink("Back to List", "Index", new {id = Model.RestaurantId}, null)
It works and takes me back to where I came from...
In my create view, when I put the same thing, I get error message that is in the heading. that Id does not have a value or is null.. So Model.RestaurantId does not have a value..
If I hard code a value ,it works such as:
#Html.ActionLink("Back to List", "Index", "Reviews", new { id = 1 }, null)
What could I be doing wrong...
I am essentially trying to follow Scott Allens MVC4 tutorial.
I am unable to understand why this is happening. I have a reviews controller. Can some one give me suggestions?
Thanks.
Have a viewmodel for your create view, with a property to store the source /parent id and use that as needed.
public classs CreateReviewVM
{
public int SourceID { set;get;}
}
and in your GET action
[HttpGet]
public ActionResult Create(int Id)
{
var vm=new CreateReviewVM { SourceID=id };
return View(vm);
}
and your create view(create.cshtml) which is strongly typed to your CreateReviewVM
#model CreateReviewVM
#Html.ActionLink("Back to List", "Index", "Reviews",
new { id = Model.SourceID }, null)
Turns out, I can use:
#Html.ActionLink("Back to List", "Index", new { id=Request.Params["restaurantId"] }, null)
and it will populate the value.
How to insert a record in MVC4 with Entity Framework?
here is my viewpage:
#foreach (var item in Model)
{
<tr>
<td>
#Html.DisplayFor(modelItem => item.brand_id)
</td>
<td>
#Html.DisplayFor(modelItem => item.brand_name)
</td>
<td>
#Html.ActionLink("ADD", "BrandList", new { item.brand_id })
</td>
</tr>
}
here is my controller code:
public ActionResult BrandList()
{
return View(db.brand.ToList());
}
[HttpPost]
public ActionResult BrandList(int id)
{
lovelist Add_Brand = new lovelist();
Add_Brand.lovelist_member = (int)Session["Member_ID"];
Add_Brand.lovelist_brand = id;
db.lovelist.Add(Add_Brand);
db.SaveChanges();
return RedirectToAction("BrandList");
}
This is what I did so far.
I cannot insert a record to my DB.
There's no any error message. I still cannt insert a record to my DB.
You have 2 actions on your controller called BrandList. The second is decorated with the [HttpPost] attribute meaning that it can only be invoked using the POST verb. But in the code you have shown you have only a hyperlink:
#Html.ActionLink("ADD", "BrandList", new { item.brand_id })
In HTML a hyperlink (anchor) sends GET request. So basically when you click on this link you are invoking the first action which doesn't do any DB saving. If you wanted to invoke the second action using a hyperlink you should rename it (because you cannot have 2 actions with the same name accessible with the same verb) and remove the [HttpPost] attribute from it:
public ActionResult SaveBrandList(int id)
{
lovelist Add_Brand = new lovelist();
Add_Brand.lovelist_member = (int)Session["Member_ID"];
Add_Brand.lovelist_brand = id;
db.lovelist.Add(Add_Brand);
db.SaveChanges();
return RedirectToAction("BrandList");
}
You will obviously need to adapt your view as well:
#Html.ActionLink("ADD", "SaveBrandList", new { item.brand_id })
There's also a possibility to use an AJAX link which would allow you to send a POST request:
#Ajax.ActionLink("ADD", "BrandList", new { item.brand_id }, new AjaxOptions { HttpMethod = "POST" })
You will need to include the jquery.unobtrusive-ajax.js script in your view for this to work. Also since you are using an AJAX call now, there's no need to be redirecting anymore from your POST controller action but simply return some partial view or JSON that could be used on the client to refresh some portion of the page.
You have missed parameter name in id and controllername . please change your action-link to
#Html.ActionLink("ADD", "BrandList","ControllerName", new {id = item.brand_id })
I have the next foreach in my cshtml page, it allows to me iterate in each Model item
#foreach (var item in Model)
{
<div class="date">
#item.pubDate
</div>
<a href="#Url.RouteUrl("Details", new { action = "Details", controller = "News", id = item.id, title = item.title })">
<img src="some route" alt="some alt" />
</a>
}
so now it's working fine and each element inside foreach loop has an url with something like
http://something.com/News/Details/1/first-title
http://something.com/News/Details/2/second-title
It's possible create urls with something like
http://something.com/News/Details/first-title
http://something.com/News/Details/second-title
but i can still sending id parameter to my controller ?
Thanks in advance
Add another route:
routes.MapRoute(
name: "NewsTitleRoute",
url: "News/Details/{id}/{title}",
defaults: new {
controller = "News",
action = "Details",
id = UrlParameter.Optional,
title = UrlParameter.Optional
}
);
In your controller declare the details method like this, with the two parameters as optional:
public ActionResult Details(int? id, string title="")
{
}
That route configuration and Details method will work for:
http://something.com/News/Details/
http://something.com/News/Details/1
http://something.com/News/Details/first-title
http://something.com/News/Details/1/first-title
You can just pass the title property for id parameter.
#Url.RouteUrl("Details",
new { action = "Details", controller = "News", id = item.title})
Then set type of id parameter as string in your action method:
public ActionResult Details(string id)
Or you can create custom route like in von-v's answer. Just make sure it's above the default route.
How do I create a partial view that has a form with assigned id?
I got as far as:
using (Html.BeginForm(?action?,"Candidate",FormMethod.Post,new {id="blah"}))
Partial view is used for both Create and Edit so first parameter ?action? will be different. I can't figure out what value of ?action? supposed to be.
UPDATE:
I guess I was not clear enough with the question. What I ended up doing is splitting Request.RawUrl to get controller name and action name:
string[] actionUrlParts = ViewContext.HttpContext.Request.RawUrl.Split('/');
using (Html.BeginForm(actionUrlParts.Length >= 2? actionUrlParts[2] : "",
actionUrlParts.Length >= 1 ? actionUrlParts[1] : "", FormMethod.Post, new { id = "blah" }))
Kind of ugly but it works. Is there a better way to get an action name inside the partial view?
Pass in the action to be performed via ViewData.
In your action that renders the view, create a ViewData item for the postback action. In your form reference this ViewData item to fill in the action parameter. Alternatively, you can create a view-only model that includes the action and the actual model as properties and reference it from there.
Example using ViewData:
using (Html.BeginForm( (string)ViewData["PostBackAction"], "Candidate", ...
Rendering actions:
public ActionResult Create()
{
ViewData["PostBackAction"] = "New";
...
}
public ActionResult Edit( int id )
{
ViewData["PostBackAction'] = "Update";
...
}
Example using Model
public class UpdateModel
{
public string Action {get; set;}
public Candidate CandidateModel { get; set; }
}
using (Html.BeginForm( Model.Action, "Candidate", ...
Rendering actions:
public ActionResult Create()
{
var model = new UpdateModel { Action = "New" };
...
return View(model);
}
public ActionResult Edit( int id )
{
var model = new UpdateModel { Action = "Update" };
model.CandidateModel = ...find corresponding model from id...
return View(model);
}
EDIT: Based on your comment, if you feel that this should be done in the view (though I disagree), you could try some logic based off the ViewContext.RouteData
<%
var action = "Create";
if (this.ViewContext.RouteData.Values["action"] == "Edit")
{
action = "Update";
}
using (Html.BeginForm( action, "Candidate", ...
{
%>
Pass nulls as action and controller. Extension will use just current action and current controller
using (Html.BeginForm(null, null, FormMethod.Post, new { id="Model" }))
Action generated for form will be the same as parent view of this partial view.
It generates
<form action="/Orders/Edit/1" id="Model" method="post">
for url http://localhost:1214/Orders/Edit/1
... and this
<form action="/Orders/Create" id="Model" method="post">
for url http://localhost:1214/Orders/Create
<% html.RenderPartial("MyUserControl", Model.ID) %>