C# MVC - Passing URL parameters to methods [duplicate] - c#

This question already has an answer here:
how to pass parameter with #url.action to controller
(1 answer)
Closed 6 years ago.
Having trouble passing url paramaters to my method in my MVC project.
Currently experiencing the following error:
The parameters dictionary contains a null entry for parameter 'id' of non-nullable type 'System.Int32' for method 'System.Web.Mvc.ActionResult SinglePost(Int32)' in 'mybloggywog.Controllers.PostController'. An optional parameter must be a reference type, a nullable type, or be declared as an optional parameter.
Call is below:
#{
foreach (var article in ViewBag.DisplayPosts)
{
<a class="ArticleLink" href="#Url.Action("SinglePost", "Post", article.Id)">#article.Title</a>
<p>#article.CreatedOn</p>
<br/>
}
}
Routeconfig:
routes.MapRoute(
"Post",
"post/{id}",
new { controller = "Post", action = "SinglePost", id = UrlParameter.Optional }
);
And method:
public ActionResult SinglePost(int id)
{
var entities = new blogEntities();
var post = entities.Set<Post>();
var postToDisplay = (from p in post
where p.Id == id
select p);
ViewBag.SinglePost = postToDisplay;
return View();
}

Try changing it to an anonymous object:
#Url.Action("SinglePost", "Post", new { id = article.Id })

Related

how to get the value of a dropdownlist to the controller in MVC

i am trying to get the value of my dropdownlist to my controller with Jquery, everything i try , gives me a null pointer for the second parameter. Here is my code :
this is the jQuery code:
<script>
$(function () {
$("#ddl").on("change", function () {
var selectedID = $("#ddl").val();
this.href = this.href.replace("idhotel", selectedID);
});
});
</script>
this is my ActionLink:
#Html.ActionLink("Voeg toe aan winkelwagentje", "Winkelwagen", new { id = Model.Id, hotelid="idhotel" }, new { #class = "btn btn-default" })
And this is my Action in the Controller:
(just header)
public ActionResult Winkelwagen(int? id,int hotelid)
{
Console.Write("Please give me the hotelid: " + hotelid);
Return View();
}
and here is the dropdownlist:
#Html.DropDownList("ddl", new SelectList(ViewBag.list, "Text", "Value"), "Select")
output dropdownlist:
error:
Server Error in '/' Application.
The parameters dictionary contains a null entry for parameter 'hotelid' of non- > nullable type 'System.Int32' for method 'System.Web.Mvc.ActionResult > Winkelwagen(System.Nullable`1[System.Int32], Int32)' > in 'TreinRittenVives.Controllers.ReizenController'. An optional parameter must > be a reference type, a nullable type, or be declared as an optional parameter.
Parameter name: parameters
in your script this.href means your select element which ID is#ddl and select can't contain href attribute. so you can do something like
<script>
$(function () {
$("#ddl").on("change", function () {
var newHref=$("a").attr("href").replace("idhotel", this.value);
$("a").attr("href",newHref);
});
});
</script>
Your second parameter is not nullable on the controller.
it should be...
public ActionResult Winkelwagen(int? id, int? hotelid)
If you want it to be a nullable type.
Regards
Craig
Try this:
$("#ddl").on("change", function () {
var selectedID = $("#ddl").val();
$(a).prop("href", $(a).prop("href").replace("idhotel", selectedID));
});
Your Error:
Server Error in '/' Application.
The parameters dictionary contains a null entry for parameter 'hotelid' of non- > nullable type 'System.Int32' for method 'System.Web.Mvc.ActionResult > Winkelwagen(System.Nullable`1[System.Int32], Int32)' > in 'TreinRittenVives.Controllers.ReizenController'. An optional parameter must > be a reference type, a nullable type, or be declared as an optional parameter. Parameter name: parameters
Reason for error:
The above error will occur most of the time in development and the main reason for the above error, is when we write a action method in the controller , we will specify the parameters as non nullable that is without the question mark in the datatype
ex.
Public void test(int a , int b)
The value must be passed, if we couldn’t pass for some reason then the above error will occur.
Solution to Error:
The best solution for the above problem is make the parameter as nullable
Nullable ex:
Public void test(int? a,int? b)
More info: https://learn.microsoft.com/en-us/dotnet/articles/csharp/programming-guide/nullable-types/

MVC Route Parameters Are Null

I'm receiving the following error that my default route parameters are null. I've used this same code on a Controller Action that didn't have any parameters in the URL and it worked fine. I know that my custom route is being called but I don't understand why startIndex and pageSize are showing up null in the action.
Error:
The parameters dictionary contains a null entry for parameter 'startIndex' of non-nullable type 'System.Int32' for method 'System.Web.Mvc.ActionResult ViewVcByStatus(System.String, Int32, Int32)' in 'AEO.WorkOrder.WebUI.Controllers.VendorComplianceController'. An optional parameter must be a reference type, a nullable type, or be declared as an optional parameter.
Parameter name: parameters
Controller:
public ActionResult ViewVcByStatus(string status, int startIndex, int pageSize) { ... }
Route:
routes.MapRoute("ViewVcByStatus", "ViewVcByStatus/{status}",
new
{
controller = "VendorCompliance",
action = "ViewVcByStatus",
startIndex = 0,
pageSize = WebConfigurationManager.AppSettings["PageSize"],
});
Link:
<a href="VendorCompliance/ViewVcByStatus?status=PROCESSED">
Also tried this link which produces the same error:
<a href="VendorCompliance/ViewVcByStatus/PROCESSED">
Try this.
public ActionResult ViewVcByStatus(string status, int? pageSize, int?startIndex)
{
return View();
}
Route.config
routes.MapRoute(
name: "ViewVcByStatus",
url: "ViewVcByStatus/{status}",
defaults: new { controller = "VendorCompliance", action = "ViewVcByStatus", startIndex = UrlParameter.Optional, pageSize = UrlParameter.Optional });
optional parameters should be declared optional in routeconfig and mark them int? in your action method, This will do the work for you. Hope this helps.This solution will work with your url pattern in your question "http://localhost:53290/VendorCompliance/ViewVcByStatus?status=PROCESSED".
Send the startIndex and pageSize with the link(I hardcoded it, use parameters instead), your actionresult is expecting all parameters that the link needs to provide, and the MapRoute will probably fall through to default Route because it can´t match it with any other route matching the one parameter you provided
<a href="VendorCompliance/ViewVcByStatus?status=PROCESSED&startIndex=0&pageSize=0">

MVC Routing Null parameters error

On my Index page I have the following link to the Details view:
#Html.ActionLink("Details", "Details", new { id = item.ClubId })|
My controller is expecting an int:
public ActionResult Details(int ClubId)
{
var club = _service.GetClub(ClubId);
var model = AutoMapper.Mapper.Map<ClubViewModel>(club);
return View(model);
}
Im getting this every time though:
The parameters dictionary contains a null entry for parameter 'ClubId'
of non-nullable type 'System.Int32' for method
'System.Web.Mvc.ActionResult Details(Int32)' in
'MyProject.Web.Controllers.ClubsController'. An optional
parameter must be a reference type, a nullable type, or be declared as
an optional parameter. Parameter name: parameters
I know this is something to do with routing however I have tried swapping UrlParameter.Optional to "" and making the ViewModel's ClubId nullable but the error remains.
If I rewire my controller to accept a Club object and pass in item from the Index view then everything is fine and the ClubId is populated in debug but I'm left with a stupidly large parameter list in the URL.
I don't really get what the problem is here?
Your controller is expecting a parameter named ClubId but you're passing a parameter called id. They need to match.
have you tried using ClubId instead of just id?

How to get parameter names in view by route values?

I am using MVC 4.
Is there a way to get action parameter names by route value.
public ActionResult Index(string id, string staffId)
{
ViewData.Add("idList", idList);
return View();
}
Suppose I have this "index" action. And the controller name is "TestController".
In the view, can I use the route value controller = "Test", action = "index", to get the parameter name list {"id, staffId"}. This route values are dynamic in view.
Use a Model. You shouldn't be putting everything in ViewData like that.
Create just a simple object that will contain the data that you need for the View, and pass the information that way.
I find the way my self. I see my question confusing. But here is what I am looking for.
var assembly = AppDomain.CurrentDomain.GetAssembliesFromApplicationBaseDirectory(
x => x.GetName().Name == "XXXX").Single();
var controllerTypes = assembly.GetTypes().Where(x => x.Name == Model.Controller + "Controller");
var controllerType = controllerTypes.Where(x => x.Namespace.Contains(Model.Area)).Single();
var action = controllerType.GetMethod(Model.Action);
var parameters = action.GetParameters();
But I am still not sure, if it's correct to put this logic in View.

ASP.NET MVC How to correctly map a parameter in url-routing

I have the following route
routes.MapRoute(
"Segnalazioni_CercaSegnalazioni",
"Segnalazioni/CercaSegnalazioni/{flag}",
new { controller = "Segnalazioni", action = "CercaSegnalazioni", flag = 7 }
);
that maps to the following methon of the class SegnalazioniController:
public ActionResult CercaSegnalazioni(int flag)
{
ViewData["collezioneSegnalazioni"] = Models.Segnalazioni.Recupera(flag);
System.Xml.Linq.XElement x = (System.Xml.Linq.XElement)ViewData["collezioneSegnalazioni"];
return View("Index");
}
How come the link http://localhost:1387/Segnalazioni/CercaSegnalazioni/1 gives me the error
The parameters dictionary contains a null entry for parameter 'flag' of non-nullable type 'System.Int32' for method 'System.Web.Mvc.ActionResult CercaSegnalazioni(Int32)' in 'RecuperoPagatiMvc.Controllers.SegnalazioniController'. To make a parameter optional its type should be either a reference type or a Nullable type.
Nome parametro: parameters
Post all your routes. It sounds like your URL is being handled by a different route than this one. Remember, the order you list your routes does matter. Therefore, if you have another route BEFORE this one that this URL can map to, it will.
MvcContrib contains route debugger. Use it and you'll see which route is called for this url. Here are some instructions how to enable it

Categories

Resources