C# mvc3 Actionlink not sending parameter in URL - c#

I am having some issues with MVC3 and Actionlink. I am dynamically building a HTML ActionLink using data passed from my model.
In the view:
#for (int i = 0; i < Model.CountriesList.Count; i++)
{
<li class="sub">#Html.ActionLink(Model.CountriesList[i].countryname,
"PageSub", new { PageID = Model.PageNo,
countryid = Model.CountriesList[i].countryid
})</li>
}
The Model.PageNo is passed from the controller and has a value. I have tested this. Every time I click on the link I am getting an error as the PageNo is not being passed as a parameter. The url outputs like below:
http://localhost/Pages/PageSub?countryid=196
I need it to be below which works when I directly enter it:
http://localhost/Pages/PageSub?PageID=136&countryid=196
This is my Controller ActionResult it directs to:
public ActionResult PageSub(int? PageID, int? countryid)
{
}
I have checked the code using developer tools and the link has been built as expected:
<li class="sub">
<a href="/Pages/PageSub?PageID=136&countryid=196">
</li>
Has anyone had similar issues? Any advice would be appreciated. Thanks

Try this:
#Html.ActionLink(Model.CountriesList[i].countryname, "PageSub", "Pages", new { PageID = Model.PageNo, countryid = Model.CountriesList[i].countryid }, null)

Related

The parameters dictionary contains a null entry for parameter

I'm attempting to, on the click of a button, complete a to-do item, therefore removing it from the list.
I'm using an ActionLink for the button:
#foreach (var item in Model)
{
<li class="#item.Priority">
#item.Text
<div class="agile-detail">
#Html.ActionLink("Done", "Complete", "Home", new { id = item.ToDoId }, new { #class = "pull-right btn btn-xs btn-primary" })
<i class="fa fa-clock-o"></i> #item.Date
</div>
</li>
}
And a very short action for the processing in the controller:
public ActionResult Complete(int todoId)
{
using (var db = new KnightOwlContext())
{
DashboardHelper dashboardHelper = new DashboardHelper(db);
dashboardHelper.CompleteToDo(todoId);
return RedirectToAction("Index", "Home");
}
}
Clicking the button generated a URL of:
http://site/Home/Complete/1
I've looked up a solution and so far it looks like it could be any number of issues. Also the ActionLink button is inside a partial view so I'm not sure if that changes anything in terms of incorrect routing setup? For routing too I'm just using the default config that comes with an MVC project in Visual Studio.
Just having trouble narrowing down the cause of the issue so where to check first?
The parameter in your method is int todoId but you not passing any value for that - your only passing a value for a parameter named id.
Change the method to
public ActionResult Complete(int id)
or change the link to use new { todoId = item.ToDoId }, but that will add a query string value, not a route value, unless you create a specific route definition with url: "Home/Complete/{todoId}"

Can I put a RedirectResult into a view link?

I have the following situation:
Into a view I define a link in this way:
<a href="#Url.Action("Edit", "Vulnerability", new { id = Model.Id })" data-mini="true" data-inline="true" data-role="button" >Annulla</a>
As you can see when the user click the link it is executed the Edit() method ot the VulnerabilityController class passing and Id value
Ok, this works fine but in this view I want have something like I have in a controller, this thing:
return new RedirectResult(Url.Action("Edit", "Vulnerability", new { id = vulnId }) + "#tab-2");
As you can see in this second version I always call the Edit() method of the VulnerabilityController class but the value of Id variable is something like "1234#tab-2"
Can I do something like this in my view and not only in my controller?
If you want to render (include) the results of some action inside your View you can use Html.Action:
#Html.Action("Edit", "Vulnerability", new { id = vulnId + "#tab-2" })
See MSDN
For doing this using Razor Syntax, you can try like this:
#Html.ActionLink("Annulla", "Edit", "Vulnerability", new { id = Model.Id },
new{ #data_mini="true", #data_inline="true", #data_role="button"})

FormCollection in MVC4 with Html Actionlink

I am using HTML ActionLink in MVC4. I need to remove QueryStrings using formCollection. How to Use it?
Here is my Code:
<div class="mainNav">
<nav>
<ul>
#for (int i = 0; i < Query.Count - 1; i++)
{
<li>#Html.ActionLink(Query[i].Parent_Menu,"ManageContent","Home", new { CmsFid = Query[i].CMSFunction_Id,ParentMenu=Query[i].Parent_Menu },new { #style = "color:#FFF;text-decoration:none" })</li>
}
#for(int i=Query.Count-1;i<Query.Count;i++)
{
<li>#Html.ActionLink(Query[i].Parent_Menu,"ManageContent","Home", new { CmsFid = Query[i].CMSFunction_Id,ParentMenu=Query[i].Parent_Menu },new {#class="last", #style = "color:#FFF;text-decoration:none" })</li>
}
</ul>
</nav>
</div>
I dont think that you will be able to get the formCollection elements in your action (using Html.ActionLink). Also if you are able you may need to parse them or type cast them for your properties. so I recomend you to have an action method like
public ActionResult ManageContent(int CmsFid,string ParentMenu)
{
}
well you can use formCollection for form post where you may have many data
if its a form post you can use like this
public ActionResult YourPostMethod(FormCollection formData)
{
int CmsFid=int.Parse(formData["CmsFid"]);
}

Drop down list at layout page - MVC

My problem: drop down list at layout page.
I've read this post: ASP.NET MVC Razor pass model to layout it's more or less similar to my problem.
In one of comments Mattias Jakobsson wrote that: "But a common solution is to use RenderAction to render parts that need their own data in the layout page".
So ok I've created layout page with #Html.Action() that render my drop dwon list with a date from the db. Everything's perfect. But...
I have two pages, for example: 'Home', 'About' and my drop down list (ddl) at layout page
How to achive that when I'm at 'Home' and I changed selection in ddl it refresh 'Home' page and when I'm at 'About' it refresh 'About' page.
How to store selected ddl value through pages?
Part of Layout.cshtml code:
.
.
<body>
<header id="top" class="grid-full-margin">
<strong id="logo" class="grid-304"><img src="/images/logo.png" ></strong>
#Html.ActionLink(#Resources.Resource.BackToIntranet, "Index", "Home", null, new {#class = "link link-home grid-position-left"})
<h1>#Resources.Resource.SiteTitle</h1>
#Resources.Resource.LayoutHelp
<nav clss="grid-896">
<ul>
<li>#Html.ActionLink(Resources.Resource.LayoutMenuItem1, "Index", "Home")</li>
<li>#Html.ActionLink(Resources.Resource.LayoutMenuItem2, "Index", "ClimaticStation")</li>
<li>#Html.ActionLink(Resources.Resource.LayoutMenuItem3, "Index", "ClimaticPoint")</li>
<li>#Html.ActionLink(Resources.Resource.LayoutMenuItem4, "Index", "IcewaterExchanger")</li>
<li>#Html.ActionLink(Resources.Resource.LayoutMenuItem5, "Index", "Pipeline")
<ul>
<li>#Html.ActionLink("Zestawienie", "YearsLength", "Pipeline")</li>
</ul>
</li>
</ul>
<div class="mod-select-list tbl-actions">
#Html.Partial("~/Views/Shared/Partials/LoginPartial.cshtml")
</div>
</nav>
</header>
<form action="#">
#Html.Action("VariantsDdl", "MyBase")
</form>
#RenderBody()
.
.
Part of MyBaseController.cs
public class MyBaseController : Controller
{
[ChildActionOnly]
public ActionResult VariantsDdl()
{
var dataFromDb = GetDataFromDB(); // it's not importstn right now
return this.PartialView("~/Views/Shared/Partials/VariantsDdlPartial.cshtml", dataFromDb);
}
.
.
}
Regards,
Marcin
ok I've managed to solve this problem and I want to know your opinion abut my solution.
_Layout.cshtml looks the same way like at first post, so belowe is only most important part for this question (drop down list at layout)
<div style="float: right;">
#Html.Action("VariantsDdl", "MyBase")
</div>
Action: VariantsDdl is implemented at MyBaseController. This action loads selected variant id from session or if it's null then from web.config (in this situation it's project requirement that at least one variant must be present at db and its id must be specified in config):
[ChildActionOnly]
public ActionResult VariantsDdl()
{
long defaultVariantID;
long.TryParse(System.Configuration.ConfigurationManager.AppSettings["DefaultVariantId"], out defaultVariantID);
if (System.Web.HttpContext.Current.Session["mySelectedVariant"] != null)
{
long.TryParse(System.Web.HttpContext.Current.Session["mySelectedVariant"].ToString(), out defaultVariantID);
}
var variants = this.db.warianties.ToList();
var items = new List<SelectListItem>();
foreach (var variant in variants)
{
var selectedItem = false;
if(variant.id == defaultVariantID)
{
selectedItem = true;
}
items.Add(new SelectListItem { Selected = selectedItem, Text = variant.nazwa, Value = variant.id.ToString() });
}
return this.PartialView("~/Views/Shared/Partials/VariantsDdlPartial.cshtml", items);
}
Partial view and post action that stores selected variant id to session:
#model IEnumerable<SelectListItem>
<label for="field">Current variant</label>
#Html.DropDownList("Varaints", Model, new { id = "variantsDdl" })
<script type="text/javascript">
$(function () {
$('#variantsDdl').change(function () {
var val = $('#variantsDdl').val()
$.ajax({
type: "POST",
url: '#Url.Action("ChangeVariant", "MyBase")' + '/' + val,
success: function (result) {
location.reload();
},
error: function (data) { alert('Error'); }
});
});
});
Partial View post action 'ChangeVariant', saves selected variant id to session:
[HttpPost]
public ActionResult ChangeVariant(long id = 0)
{
System.Web.HttpContext.Current.Session["mySelectedVariant"] = id;
return null;
}
This is solution for my requirements:
1. DDL at layout
2. Refresh current page at DDL 'onchange'
3. Keep selected DDL value through pages
Please comment if it's appropriate solution or maybe should I go different way?
Regards,
Marcin

Load View again by passing updated parameter to the same Controller MVC 3

I want to load the same view again by passing updated parameter from text input on the link click. I tried to use something like <a href="#Url.Action("Index", "Home", new {id = "txtCount".value }). Not sure if there is even a way to do this. I know I could use partial but I want to reload the whole page with updated parameter. Thanks in advance for any help.
Controller
[HttpGet]
public ActionResult Index(int id)
{
return View(id);
}
View
#model int
#using (#Html.BeginForm())
{
<input id="txtCount" value="1" />
Update
for (int i = 0; i < Model; i++)
{
<div>#i </div>
}
}
Maybe something like this
Go!
and binding with jquery
$("#mylink").click(function(){
document.location.href = '#Url.Content("~/Controller/Action")' + $("#mytxt").val();
return false;
});
Obviously with the proper validations if the textbox is empty and all that stuff.
You cannot add the id value to the #Url.Action because it is processed before on the server side, before the page is rendered

Categories