I need to pass 2 parameters id and date from view to controller side on the click event. It may be basic question but i am not able to do so.
I tried simply this code
Code <a href='/Abc/Details/id?=#website_id, date?=#date' class="" id="prev" >Prev</a>
and how to get those parameter at controller side.
I don't want to use "Ajax" or JavaScript if possible
First of all either you need to create custom route or enable MapMvcAttributeRoutes in your routeconfig file by adding below line of code.
routes.MapMvcAttributeRoutes();
Then in your controller above your defined action add something like below.
[Route("/Abc/Details/{id}/{date}")]
If you want to make it nullable then.
[Route("/Abc/Details/{id?}/{date?}")]
Your action method will be something like below.
[Route("/Abc/Details/{id?}/{date?}")]
public ActionResult Details(int id, string date)
Use #Html.ActionLink instead of hard coding your links.
If you wanted to go with custom route then add it above your default route.
routes.MapRoute(
"MyCustomRoute",
"Archive/{entrydate}",
new { Controller = "ABC", action = "Details",Id = UrlParameter.Optional,Date = UrlParameter.Optional});
Now in your view
#Html.RouteLink("Link Text", "MyCustomRoute", new { Id = YourId, Date=YourDate})
I found it easier to declare your variables in the Controller Action:
public IActionResult Create(string FirstName, string MiddleName, string
LastName, string ADUsername, string ADId, string ADName, string ADemail)
{
//do this
}
Then you can assign the variables by name in the View:
<a asp-controller="Employees" asp-action="Create" asp-route-
FirstName="#item.FirstName" asp-route-MiddleName="#item.MiddleName" asp-
route-LastName="#item.LastName" asp-route-ADUsername="#item.ADUsername" asp-
route-ADId="#item.ADId" asp-route-ADName="#item.ADName" asp-route-
ADemail="#item.ADemail">Add Employee</a>
I found #Mighty Ferengi answer very useful. Thanks man!
public IActionResult Create(string FirstName, string MiddleName, string
LastName, string ADUsername, string ADId, string ADName, string ADemail)
{
//do this
}
In Razor
<a asp-controller="Employees" asp-action="Create" asp-route-
FirstName="#item.FirstName" asp-route-MiddleName="#item.MiddleName" asp- route-LastName="#item.LastName"
asp-route ADUsername="#item.ADUsername"
asp-route-ADId="#item.ADId" asp-route ADName="#item.ADName"
asp-route- ADemail="#item.ADemail">Add Employee</a>
Related
Okie, I am trying to finish a product dispkay for a client, in my code I have this
#foreach (var item in Model)
{
<div class="itemcontainer">
<p class="button">#Html.ActionLink(item.Category, item.Category) (#item.Count)</p>
</div>
}
Which gives me the link (URL) of Products/Categories, now what do I need to get to my ultimate goal of (for example) Products/Braceletsss. Do I have to write a custom route, if so can someone show me an example, I'm still trying to get my head around this.
**EDIT*
I can provide more code if it's needed :)
[HttpGet, Route("products/{categoryName}")]
public IActionResult GetProductsByCategoryName(string categoryName) {
... code to retrieve products by category name
The above is one way to do it, the way that I prefer at least. When you access the route /products/nine-millimeter-handguns, then in your action, the categoryName variable will have the value nine-millimeter-handguns. You can then use that string value to look up all of the products in that category and return them to the client.
The other way to do it is in your global route config in Startup.cs. If you do it this way, you don't need the [Route] attribute on the action method:
public void Configure(IApplicationBuilder app) {
...
app.UseMvc(routes => {
routes.MapRoute(null, "products/{categoryName}", new {
controller = "Products", action = "GetProductsByCategoryName"
});
});
}
I prefer the former attribute approach because it keeps the routes closer to the controllers & actions that they map to. But both will accomplish the same thing.
In order to render a link to this route from a view, you would pass in the categoryName to the ActionLink html helper method:
#Html.ActionLink(item.Category, item.Category, new {
categoryName = "nine-millimeter-handguns"
})
I have a ViewModel that I would like to use to populate the QueryString, almost the opposite of the binding that MVC does out of the box. So for the model that looks like this:
public class SearchViewModel
{
public string Keywords { get; set; }
// more properties here
}
I would hope to be able to do something like this:
string querystring = AspMagicMethods.GetQueryStringFromViewModel(searchViewModel);
// querystring == ?keywords=booyah&...
Obviously I could go through each property and create the string myself, but I was wondering if there's anything built into the framework that might be of assistance.
You can use following method of MVC to do so from any controller action.
var myModel = new SearchViewModel{Keywords ="test"};
RedirectToAction("actionName", "controllerName", myModel)
After reviewing A LOT of questions and Internet data, I've solved a problem of mine with getting URL parameter from MVC3 application correctly.
Thing is that there wasn't a fault in coding, but in routing (I'm not so good with routing...).
Here's the current issue.
http://localhost:51561/Report/Details/1
This is the way my application presents Report details, which is good. But when it does it like this, I can't get value from URL parameter, like this
Request.QueryString["id"]
But, when I manually type in URL http://localhost:51561/Report/Details?id=1 it works...
Thing is i like the first URL type, but I don't know how to get parameter from it...
Help, please...
Update:
My Controller actions:
public ViewResult Details(int id)
{
Report report = db.Reports.Find(id);
ViewBag.TestID = Request.QueryString["id"].ToString();
return View(report);
}
public ActionResult Show(int id)
{
Report report = db.Reports.Find(id);
var imageData = report.Image;
return (File(imageData, "image/jpg"));
}
My View:
<div class="display-label">Picture</div>
<div class="display-field">
<img alt="image" src="<%=Url.Action("Show", "Report", new { id = ViewBag.TestID })%>" width="200px" />
</div>
First of all, you shouldn't use Request.QueryString in your application. Apart from that, in the first URL, you don't have a query string, and thus you can't access it (also read this article on msdn about Request.QueryString).
I also would like to suggest you to go through the basic tutorial of ASP.NET MVC3, to be found here. Many things like your question are thoroughly explained there.
To answer your question now, in your first URL example, the 1 in the URL is a parameter of your action (the Details action). You have to add this parameter to your method (action):
public ActionResult Details(int id)
UPDATE:
You have apparently the right action (method) declaration. Now, you can just use the parameter id. So change the Request.QueryString["id"] just by the variable (parameter) id.
public ViewResult Details(int id)
{
Report report = db.Reports.Find(id);
ViewBag.TestID = id;
return View(report);
}
There is no need to apply ToString() on the id, you shouldn't make it when it isn't necessary (you might need it somewhere else, later or so). Just put it in the ViewBag as the original type.
Your Show() method is good :). You have now the id parameter as you needed. (Try to avoid too many parentheses, it makes it look messy and now so clear.)
public ActionResult Show(int id)
{
Report report = db.Reports.Find(id);
var imageData = report.Image;
return File(imageData, "image/jpg");
}
You're not supposed to use Request.QueryString["id"] in MVC
Just add id parameter to your ReportController.Details action:
public ActionResult Details (int id)
The above is assuming you have a default route setup in Global.asax:
routes.MapRoute(
"Default", // Route name
"{controller}/{action}/{id}", // URL with parameters
new { controller = "Home", action = "Index", id = UrlParameter.Optional } // Parameter defaults
);
Is it possible to overload the action methods based on number of parameters in request?
Eg:
1.
domain.com/List/Filter/ByName
invokes -> public ActionResult Filter(string criteria1)
2.
domain.com/List/Filter/ByName/ByRanking
invokes -> public ActionResult Filter(string criteria1, string criteria2)
I'm using asp.net mvc2.
Action methods cannot be overloaded based on parameters because there would be no reasonable way to disambiguate a URL into multiple overloaded methods.
What you can do, though is either this:
public ActionResult Filter(string criteria1, string criteria2)
and then check whether criteria2 is null to filter only by name.
Alternatively, you can use ActionNameAttribute to decorate your action methods
[ActionName("FilterByName")]
public ActionResult Filter(string criteria1)
[ActionName("FilterByNameAndRanking")]
public ActionResult Filter(string criteria1, string criteria2)
and then use that name in route registration. This approach, however, can lead to much confusion.
If I'm not mistaken the best way to do this would be to add two different controller methods and map them to two different Urls.
public ActionResult Filter1(string criteria1);
public ActionResult Filter2(string criteria1, criteria2);
Then you have two route definitions:
This will map this URL List/Filter/xxCriteria/ to the first controller
routes.MapRoute(
"Filter", // Route name
"{controller}/Filter/{criteria1}", // URL with parameters
new { controller = "List", action = "Filter1", criteria="" } // Parameter defaults
);
This will map this URL List/Filter/xxCriteriaName/xxxCriteriaRank to the second controller. Without this route you could still map a url to the second method, but it would look like : List/Filter/?criteria1=xx&criteria2=xx
routes.MapRoute(
"Filter2", // Route name
"{controller}/Filter/{criteria1}/{criteria2}", // URL with parameters
new { controller = "List", action = "Filter2", criteria1 = "", criteria2 = "" } // Parameter defaults
);
Hope it helped.
I'm trying out asp.net mvc for a new project, and I ran across something odd. When I use the MVC UI helpers for textboxes, the values get persisted between calls. But, when I use a series of radio buttons, the checked state doesn't get persisted.
Here's an example from my view.
<li>
<%=Html.RadioButton("providerType","1")%><label>Hospital</label>
<%=Html.RadioButton("providerType","2")%><label>Facility</label>
<%=Html.RadioButton("providerType","3")%><label>Physician</label>
</li>
When the form gets posted back, I build up an object with "ProviderType" as one of it's properties. The value on the object is getting set, and then I RedirectToAction with the provider as a argument. All is well, and I end up at a URL like "http://localhost/Provider/List?ProviderType=1" with ProviderType showing. The value gets persisted to the URL, but the UI helper isn't picking up the checked state.
I'm having this problem with listbox, dropdownlist, and radiobutton. Textboxes pick up the values just fine. Do you see something I'm doing wrong? I'm assuming that the helpers will do this for me, but maybe I'll just have to take care of this on my own. I'm just feeling my way through this, so your input is appreciated.
Edit: I just found the override for the SelectList constructor that takes a selected value. That took care of my dropdown issue I mentioned above.
Edit #2: I found something that works, but it pains me to do it this way. I feel like this should be inferred.
<li>
<%=Html.RadioButton("ProviderType","1",Request["ProviderType"]=="1")%><label>Hospital</label>
<%=Html.RadioButton("ProviderType", "2", Request["ProviderType"] == "2")%><label>Facility</label>
<%=Html.RadioButton("ProviderType", "3", Request["ProviderType"] == "3")%><label>Physician</label>
</li>
Hopefully someone will come up with another way.
If you give the radio buttons the same name as the property on your model, then MVC will automatically set the checked attribute on the appropriate button.
I think this relies on having a strongly typed Model.
What you need is something like this in your view:
<% foreach(var provider in (IEnumerable<Provider>)ViewData["Providers"]) { %>
<%=Html.RadioButton("ProviderType", provider.ID.ToString(), provider.IsSelected)%><label><%=provider.Name%></label>
<% } %>
And then in your controller have this:
var providers = GetProviders();
int selectedId = (int) Request["ProviderType"]; // TODO: Use Int32.TryParse() instead
foreach(var p in providers)
{
if (p.ID == selectedId)
{
p.IsSelected = true;
break;
}
}
ViewData["Providers"] = providers;
return View();
The Provider class will be something like this:
public class Provider
{
public int ID { get; set; }
public string Name { get; set; }
public bool IsSelected { get; set; }
}
The form shouldn't be posting to the querystring, unless you forgot to specify the form as method="POST". How are you specifying the form? Are you using ASP.NET MVC Beta?
I'm using vs2010 now, it works like:
<%=Html.RadioButton("ProviderType","1",Model.ProviderType==1)%><label>Hospital</label>
looks better?
Well logically it would not persist, there is no session state. Think of it as an entirely new page. In order to get your radio buttons to populate you need to persist back something like ViewData["ProviderType"] = 3 to have the radiobutton repopulate with its data.
I've made this HTML Helper extension:
<Extension()> _
Public Function RadioButtonList(ByVal helper As HtmlHelper, ByVal name As String, ByVal Items As IEnumerable(Of String)) As String
Dim selectList = New SelectList(Items)
Return helper.RadioButtonList(name, selectList)
End Function
<Extension()> _
Public Function RadioButtonList(ByVal helper As HtmlHelper, ByVal Name As String, ByVal Items As IEnumerable(Of SelectListItem)) As String
Dim sb As New StringBuilder
sb.Append("<table class=""radiobuttonlist"">")
For Each item In Items
sb.AppendFormat("<tr><td><input id=""{0}_{1}"" name=""{0}"" type=""radio"" value=""{1}"" {2} /><label for=""{0}_{1}"" id=""{0}_{1}_Label"">{3}</label></td><tr>", Name, item.Value, If(item.Selected, "selected", ""), item.Text)
Next
sb.Append("</table>")
Return sb.ToString()
End Function
Then in the view:
<%= Html.RadioButtonList("ProviderType", Model.ProviderTypeSelectList) %>
In the controller the option is mapped automagically using the standard:
UpdateModel(Provider)
Works like a charm. If you are tablephobic, change the markup generated.
View:
<%=Html.RadioButton("providerType","1")%><label>Hospital</label>
<%=Html.RadioButton("providerType","2")%><label>Facility</label>
<%=Html.RadioButton("providerType","3")%><label>Physician</label>
Controller:
public ActionResult GetType(FormCollection collection)
{
string type=collection.Get("providerType");
if(type=="1")
//code
else if(type=="2")
//code
else
//code
return View();
}