I keep getting a Compilation Error and can't find matching overloaded method. I've tried a couple ways (variable, variable.toString). Below is the latest try.
When I click on the day (ex: 2) on the calendar the ActionLink should send the querystring: "Index?day=2".
#{ string dayAsString = startCount.ToString();}
<div><span>#Html.ActionLink(#startCount.ToString, "Index?day=" + dayAsString , "Event")</span></div>
Do this
<div>
<span>
#Html.ActionLink(startCount.ToString(), "Index", new { day = startCount })
</span>
</div>
The last parameter creates an anonymous object with the property day and value startCount. ActionLink knows to convert that into a querystring using the property name and the property value.
More details here http://msdn.microsoft.com/en-us/library/dd492936.aspx
Edit:
If you want to target a specific controller, do this
#Html.ActionLink(startCount.ToString(), "Index", new { controller = "Event", day = startCount })
You can also do this
#Html.ActionLink(startCount.ToString(), "Index", "Event", new { day = startCount }, null)
but I don't like passing null as a parameter.
Here's a list of all the overloads: http://msdn.microsoft.com/en-us/library/dd505040.aspx
You can also just cycle in the intellisense.
This should work
#Html.ActionLink(#startCount.ToString,"Index","Yourcontroller",new { day=#startCount.ToString()} , null)
replace Yourcontroller with your controller name
Related
I'm new to ASP.NET and I'm struggling to understand how routing works. In my project I've managed to create routing for; login, logout, create new user and delete user.
I've created cards containing dates and a stretched-link with the purpose to act as a booking-table (click on a card to book the said time).
View code:
When I click on the link I want to pass forward the user as a string and the time as DateTime(or string). If I replace the url.action argument "TimeSlot.ToString()" with null my routing "works", but of course with the exception that only the user is passed forward to my controller.
#model MyProject.Models.BookingSchedule
...
<div class="row" style="padding-top: 50px; border:solid">
#{ foreach (var TimeSlot in Model.GetAllAvailableTimes())
{
<div class="col-sm-1" style="padding:10px">
<div class="card text-md-center">
<a class="stretched-link" href="#Url.Action("BookTime","Booking",new { user = Model.UserName }, TimeSlot.ToString())">#TimeSlot.ToString()</a>
</div>
</div>
}
}
</div>
Controller:
So far I've just created a mockup code for my controller, its only purpose is to reload my view and redisplay available times together with the time I've booked. For now, I just want to see if my routing passes all parameters to my controller (which it doesn't):
public ActionResult BookTime(string user, string Time)
{
return View("BookingPage", bookingSchedule(user));
}
Routing:
routes.MapRoute(
"BookTime",
"Booking/{Action}/{user}/{time}",
new { controller = "Booking", action = "BookTime", user = UrlParameter.Optional, time = UrlParameter.Optional }
);
When I run my code I get the following error:
How do I create a routing with two or more parameters and what are the key aspects that I need to keep in mind?
I've tried to get knowledge from the Microsoft-docs but as I've not yet managed to overcome this issue I'm hoping someone here could explain it.
https://learn.microsoft.com/en-us/aspnet/core/mvc/controllers/routing?view=aspnetcore-6.0#attribute-routing
If I set my href to "href="#Url.Action("BookTime","Booking",new { user = Model.UserName }, TimeSlot.ToString())" then I get the error message above.
If I set href to href="#Url.Action("BookTime","Booking",new { user = Model.UserName }, null)" it will route correctly but of course it doesn't pass my parameters (see photo below):
(in the picture/code above I changed the name of the controller to BookingPage as is the name of my viewpage. I did this to rule out any routing issues)
just add an attribute route
[Route("~/Booking/BookTime/{user?}/{time?}",
public ActionResult BookTime(string user, string Time)
{
return View("BookingPage", bookingSchedule(user));
}
and fix your link
href= ( "Book Time",
"BookTime",
"Booking",
new { user = Model.UserName, time = TimeSlot.ToString() },
null )
I have 2 links for language switch
<a class="dropdown-item"
href="#Url.Action(ViewContext.RouteData.Values["action"].ToString(), ViewContext.RouteData.Values["controller"].ToString(), new { language = "en" }, null)"
style="color:#333;">English</a>
<a class="dropdown-item"
href="#Url.Action(ViewContext.RouteData.Values["action"].ToString(), ViewContext.RouteData.Values["controller"].ToString(), new { language = "ar" }, null)"
style="color:#333;">Arabic</a>
it works fine there is only controller and action in url
but when there is optional param like id for detail and edit action than it do not work as expected.
I think I have to change null (this last param) with something but I am new and googled a lot but not getting anything worthy, Please help me.
It would be better if the solution work for n number of optional params instead of only one Id, but for now that will also be acceptable.
it would be better if the solution work for n number of optional params instead of only one Id
for getting all passed querystring parameter on MVC controller side better to use
Request.QueryString
Request.QueryString is NameValueCollection and you get value passed in querystring parameter in your actionlink.
i have tried that looks like below
<a class="dropdown-item" href="#Url.Action(ViewContext.RouteData.Values["action"].ToString(), ViewContext.RouteData.Values["controller"].ToString(), new { language = "ar",id="100",studentid = 1,studentName = "abc" }, null)" style="color:#333;">Arabic</a>
and your mvc Controller look like below
public ActionResult About(int id)
{
var querystring = Request.QueryString;
// in querystring you get all value like below screenshot
var studentName = querystring["studentName"]; // access parameter like
ViewBag.Message = "Your application description page.";
return View();
}
you can get all parameter that you passed in your controller.
I am trying to create a CustomMembershipProvider. When the user clicks the login, I want to display "welcome UserName!" inside a PartialView that is contained in the Shared/_layout .cshtml
Here is the controller class:
[ChildActionOnly]
public ActionResult WelcomeMessage()
{
var userName = this.HttpContext.Session["LoggedInUser"];
WelcomeViewModel wView = new WelcomeViewModel();
if (userName != null)
{
User user = this.db.Users.FirstOrDefault(x => x.UserName == userName);
wView.userId = user.Id;
wView.Message = user.UserName;
}
return PartialView(wView);
}
Here is the PartialView code:
#model MvcApplication1.ViewModels.WelcomeViewModel
#Html.ActionLink("Welcome " + Model.Message + "!", "Edit", "Account", new { id = Model.userId })
I get the view to render correctly, however when I click the Hyperlink, I am presented with the following error:
The parameters dictionary contains a null entry for parameter 'id' of non-nullable type 'System.Int32' for method 'System.Web.Mvc.ViewResult Details(Int32)' in 'MvcApplication1.Controllers.AccountController'. An optional parameter must be a reference type, a nullable type, or be declared as an optional parameter.
It appears that the Edit Action is called with id = null, however, the user name is displaying correctly. I was initially using ViewBag and have switched to ViewModel as per the SO solution here.
Thanks in advance.
Try with this
#Html.ActionLink("Welcome " + Model.Message + "!", "Edit", "Account", new { id = Model.userId }, null)
The problem is that you set the htmlAttributes parameter of the ActionLink method.
You are hitting the wrong overload of #Html.ActionLink, you need this one
Html.ActionLink("Welcome " + Model.Message + "!", // Display text
"Edit", // ActionMethod
"Acount", // Controller Name.
new { Model.Id }, // Route arguments.
null // htmlArguments
)
Basically, you need to pass the htmlAttributes parameter to hit the right overload, you can pass this as null if you don't need to set any.
Well it seems like you're using the wrong overload, give this a shot:
#Html.ActionLink("Welcome " + Model.Message + "!", "Edit", "Account",
new { id = Model.userId },
null)
I have this method in my controller called "DirectorySearchController"
public ActionResult PersonDetails(FoundPerson person) //for some reason person is null here
{
DirectoryViewModel viewModel = new DirectoryViewModel();
viewModel.person = person;
return View(viewModel);
}
When I pass some parameters to it from the view using Html.Actionlink it returns a null value
<ul data-role="listview">
#if (ViewBag.Message == "NO RESULTS FOUND")
{
<li>#ViewBag.Message</li>
}
else
{
foreach (var employee in Model)
{
<li>
<div class="ui-grid-b">
<div class="ui-block-a" style="width:20%; vertical-align:middle"><img src="#employee.pictureURL" width="40px" height="40px"/></div>
<div class="ui-block-b" style="width:80%; vertical-align:middle">#Html.ActionLink(employee.name, "PersonDetails", "DirectorySearch", new { person = employee}, null)</div>
</div>
</li>
}
}
</ul>
But the funny thing is that when I pass the parameter without using the "new" keyword it passes the correct value. However, the problem is I need to pass multiple parameters so I need to use the "new" keyword.
<div class="ui-block-b" style="width:80%; vertical-align:middle">#Html.ActionLink(employee.name, "PersonDetails", "DirectorySearch", employee, null)</div>
I think you are not using the correct overload of ActionLink. Try with either of these
The first one should mostly work according to your case:
<%=Html.ActionLink(employee.Name, "PersonalDetails", "DirectorySearch", new { person = employee }, null)%>
<%=Html.ActionLink(employee.Name, "PersonalDetails", new {person = employee})%>
Just a recommendation here. Ideally I'd use an Input submit to post the data to the Controller. You may either use a Model class OR FormCollection in the controller side to retrieve the values you entered in the View.
You should not pass model to the controller action like new { person = employee } in Html.ActionLink. Because what happens is, when you generate the action link the object you pass is converted into RouteValueDictionary which will be passed to the UrlHelper to append the route dictionary values to the link.
When you pass an anonymous object like in the first case the RouteValueDictionary stores a single parameter with name person and to set the value it sees that you have passed an object, it can't serialize the complete instance and set it to the single property so all it does is set the type name of the model Employee as the value to the person. So you will see the generated link as http://someserver/DirectorySearch/PersonDetails?person=Models.Employee
If you pass an instance like you did in the second case then it iterate all the properties and create key/value pairs, while the keys are the property names and the values are the property values, finally they all appended to the link as querystrings. In the case the generated url will be http://someserver/DirectorySearch/PersonDetails?Property1=Value1&Property2=Value2
Correct
#Html.ActionLink(employee.name, "PersonDetails", "DirectorySearch", employee, null)
Wrong
#Html.ActionLink(employee.name, "PersonDetails", "DirectorySearch", new {person = employee }, null)
You can use anonymous object to pass route parameters to the action link but at the time you should not pass reference types but built-in types like integer, string..
Ex.
#Html.ActionLink(employee.name, "PersonDetails", "DirectorySearch",
new { Id = 23, Name = "Mark" }, null)
I've got a view that defines a form as
<% using (Html.BeginForm( "Update", "CcisCase", FormMethod.Post, new { id = "ccisEditForm" } ))
with a submit button:
In the RegisterRoutes method (in the HttpApplication-derived class in global.asax.cs), I've got:
routes.IgnoreRoute( "{resource}.axd/{*pathInfo}" );
routes.MapRoute(
"CcisCase",
"CcisCase/{action}/{cmDatabaseId}/{caseId}",
new { Controller = "CcisCase", Action = "CcisCaseEdit", caseId = "" } );
The url generated by MVC ends with "/Update" but there are no parameters. What am I doing wrong?
Thanks,
Bob
What parameters are you expecting to see? A post does not append parameters to the querystring, a FormMethod.Get would. And, that overload with the id is the collection of HTML attributes to render for the tag (which I'm assuming you knew, but just in case).
HTH.
Your route contains a parameter {caseId} but your BeginForm only defines an id value.
new {id = "cssEditForm"}
You need something like this to include the caseId value
using (Html.BeginForm( "Update", "CcisCase", FormMethod.Post, new { caseId = 1, id = "ccisEditForm" }
If your action isn't using the id="ccisEditForm" value then you can remove that for less code clutter.
I figured out what my problem was. I had to pass the existing route data as follows:
using (Html.BeginForm( "Update", "CcisCase", ViewContext.RouteData.Values, FormMethod.Post, new Dictionary<string, object> { { "id", "ccisEditForm" } } ))