html.actionlink - asp.net-mvc

i'm just starting to use asp.net mvc..
since i'm not familiar with it, i just want to ask a question about actionlink html helper..
i have this code in my index.aspx home view..
<% Dim _news As datatable = ViewData.Model%>
<% For count As Integer = 0 To _news.Rows.Count - 1%>
<% Dim id As Integer = _news.Rows(count).Item("IDnews")%>
<%=_news.Rows(count).Item("newsTitle")%>
<p>
<%=_news.Rows(count).Item("newsContent")%><br />
<%=Html.ActionLink("Read More..", "NewsPublic", "Administration", New With {id})%>
</p>
<%Next%>
if i click the actionlink, i was expecting it will render me to this url:
/Administration/NewsPublic/7
but rather it gives me this url :
/Home/NewsPublic?Length=14
does actionlink pass id in the same controller only?
thank you in advance!

To render link to /Administration/NewsPublic/7 you should use
<%=Html.ActionLink("Read More..", "NewsPublic", "Administration",
New With {.id = 7}, Nothing)%>
Fifth parameter makes compiler to choose
ActionLink(string linkText, string actionName, string controllerName,
object routeValues, object htmlAttributes)
extension method overload instead of
ActionLink(string linkText, string actionName, object routeValues,
object htmlAttributes)
And don't forget to add parameter assignment
New With {.id = 7}
instead of
New With {.id}

By default, Html.ActionLink will use the current controller. But there are about a dozen overloads of ActionLink(), and there are multiple versions of it that will accept a controller parameter. Try:
Html.ActionLink("Read More...",
"NewsPublic",
"Administration",
New With { .id = id },
null)

Related

Cannot assign attributes to form using Html.BeginForm

I have a form begun with the Html.BeginForm() helper method:
#using (Html.BeginForm(
null,null, new { #id = "MaintenanceForm", #class = "datatable", #nonvalidate="nonvalidate" }
))
and the form is rendered as:
<form action="(controller's name)/(current action's name)/MaintenanceForm?class=datatable" method="post">
The attributes such as id, class, and nonvalidate aren't assigned. Also I do not want a default Http Method. What can I do?
Your current code is matching with the below overload of BeginForm method
public static MvcForm BeginForm(
this HtmlHelper htmlHelper,
string actionName,
string controllerName,
object routeValues
)
The third parameter here is an object for the route values. These will be added as the querystring key value(s) to your form's action attribute value. That is the reason you are seeing those big url as the action attribute value.
If you want to specify the html attributes( Id,class etc), Use this overload which has a fourth parameter which takes the html attributes. The third parameter is the FormMethod.
public static MvcForm BeginForm(
this HtmlHelper htmlHelper,
string actionName,
string controllerName,
FormMethod method,
object htmlAttributes
)
This should work.
#using (Html.BeginForm("Create", "Post",FormMethod.Post,
new { #id = "MaintenanceForm", #class = "datatable", #nonvalidate = "nonvalidate" }))
{
}
Replace Create and Post with your action method name and controller name.

MVC 4: Sending a ViewModel from a View to another View. Some properties are getting null

I have a simple view like this:
#using MyProject.WebClient.Models
#model LoginClienteModel
<h1>#ViewBag.Title</h1>
#{
<text>
<h2>
<span>Olá #Model.Login . </span>
</h2>
<h3>
<span>Info: (#Model.ProperyOne)</span>
</h3>
</text>
}
<br/>
#Html.ActionLink("Option 1", "OptOne", "Home", new {pdModel = new OptOneModel{Login = Model.Login,Data = DateTime.Now.Date}});
When this view is showed, all data from model is displayed correctly. You can see I've another ActionLink, pointing to action OptOne. That action requires a parameter pdModel of type OptOneModel. As you can see, I instantiate it using current model values.
But when my Action is executed, Login property is null, only Data is not null.
public ActionResult OptOne(OptOneModel pdModel)
{
return View(pdModel); // <-- Here only Data property is not null
}
I'm lost. I can't see what is wrong with that.
Unfortunately, you can't pass a complex type into a route value that way for an ActionLink. Manual invocation of an Action, I believe you can, but not for a link. So:
#Html.ActionLink("Option 1", "OptOne", "Home", new {pdModelId = Model.YourUniqueId, dateRendered = DateTime.Now.Date});
Meanwhile, server side:
public ActionResult OptOne(int pdModelId, DateTime dateRendered)
{
// retrieve model again based on your Id
return View(pdModel);
}
You cannot use hyperlink to pass Model. It only work with Post.
Instead, you can use routeValues to generate query string.
#Html.ActionLink("Option 1", "OptOne", "Home",
new { Model.Login, Data = DateTime.Now.Date }, null)
public ActionResult OptOne(string login, DateTime data)
{
// Do something with login and data.
return View();
}
Use either ActionLink overload variation,
ActionLink(string linkText, string actionName, string controllerName, object routeValues, object htmlAttributes)
#Html.ActionLink("Option 1", "OptOne", "Home", new OptOneModel{ Login = Model.Login, Data = DateTime.Now.Date}, null);
OR
ActionLink(string linkText, string actionName, object routeValues)
#Html.ActionLink("Option 1", "OptOne", new OptOneModel{ Login = Model.Login, Data = DateTime.Now.Date});
hope this helps.

Passing parameter to controller action from a Html.ActionLink

Is there anything wrong with this html? I want to have a link in the masterpage to navigate to "CreateParts" view. I have action 'CreateParts' which have a parameter parentPartId in the controller 'PartList'.
<li id="taskAdminPartCreate" runat="server">
<%= Html.ActionLink("Create New Part", "CreateParts", "PartList", new { parentPartId = 0 })%></li>
My controller action is like
public ActionResult CreateParts(int parentPartId)
{
HSPartList objHSPart = new HSPartList();
objHSPart.Id = parentPartId;
return View(objHSPart);
}
When I click on 'Create New Part' in the menu in SiteMaster, I get exception. Please help me out of this.
You are using incorrect overload. You should use this overload
public static MvcHtmlString ActionLink(
this HtmlHelper htmlHelper,
string linkText,
string actionName,
string controllerName,
Object routeValues,
Object htmlAttributes
)
And the correct code would be
<%= Html.ActionLink("Create New Part", "CreateParts", "PartList", new { parentPartId = 0 }, null)%>
Note that extra parameter at the end.
For the other overloads, visit LinkExtensions.ActionLink Method. As you can see there is no string, string, string, object overload that you are trying to use.
You are using the incorrect overload of ActionLink. Try this
<%= Html.ActionLink("Create New Part", "CreateParts", "PartList", new { parentPartId = 0 }, null)%>
Addition to the accepted answer:
if you are going to use
#Html.ActionLink("LinkName", "ActionName", "ControllerName", new { #id = idValue, #secondParam= = 2 },null)
this will create actionlink where you can't create new custom attribute or style for the link.
However, the 4th parameter in ActionLink extension will solve that problem. Use the 4th parameter for customization in your way.
#Html.ActionLink("LinkName", "ActionName", "ControllerName", new { #id = idValue, #secondParam= = 2 }, new { #class = "btn btn-info", #target = "_blank" })

Providing ID in ActionLink() or RouteLink()?

I'm new to MVC and would like to add a link to something like ~/Destinations/35, where it would refer to the Index view of the Destinations controller, and 35 is the ID of the destination to be displayed.
Neither ActionLink() or RouteLink() appear to allow me to create a link such as this.
Also, I tried something like this:
<table>
#foreach (var d in ViewBag.Results)
{
<tr>
<td>
#Html.ActionLink(
String.Format("<b>{0}</b>", #Html.Encode(d.Title)),
"Details", "Destinations")
</td>
</tr>
}
</table>
But I get the following error on the ActionLink line, which I don't understand.
'System.Web.Mvc.HtmlHelper' has no applicable method named 'ActionLink' but appears to have an extension method by that name. Extension methods cannot be dynamically dispatched. Consider casting the dynamic arguments or calling the extension method without the extension method syntax.
Can someone help me create this link?
The first problem with your code is that you are trying to use HTML in the link text (the <b> tags) which is not possible because by design it always HTML encodes.
So assuming you didn't want HTML in the link you could do this:
#Html.ActionLink(d.Title, "Details", "Destinations", new { id = "35" }, null)
And assuming you need HTML inside the anchor you have a couple of possibilities:
Write a custom ActionLink helper which won't HTML encode the text (recommended) and then use like this:
#Html.MyBoldedActionLink(d.Title, "Details", "Destinations", new { id = "35" }, null)
Something along the lines:
<a href="#Url.Action("Details", "Destinations", new { id = "35" })">
<b>#d.Title</b>
</a>
and since I recommend the first approach here's a sample implementation of the custom helper:
public static class HtmlExtensions
{
public static IHtmlString MyBoldedActionLink(
this HtmlHelper htmlHelper,
string linkText,
string actionName,
string controllerName,
object routeValues,
object htmlAttributes
)
{
var anchor = new TagBuilder("a");
anchor.InnerHtml = string.Format("<b>{0}</b>", htmlHelper.Encode(linkText));
var urlHelper = new UrlHelper(htmlHelper.ViewContext.RequestContext);
anchor.Attributes["href"] = urlHelper.Action(actionName, controllerName, routeValues);
anchor.MergeAttributes(new RouteValueDictionary(htmlAttributes));
return new HtmlString(anchor.ToString());
}
}

How to unpack htmlAttributes in a span tag in ASP.NET MVC

I have htmlAttributes generated - originally for the purpose of creating a link with the attribute using Html.ActionLink.
Now, based on some condition, I would like to create a <span> tag instead and put the attributes in there. Is there anyway it can be done easily ?
Eg: something like:
<span <%= htmlAttributes.Unpack() %> > Some txt </span>
OR
<%= Html.SpanTag("Some txt", htmlAttributes) %>
OR anything similar without wresling too much with the already generated htmlAttribues?
Thanks
You could easily build an Html.Span Extension something like :
public static MvcHtmlString DatePicker(this HtmlHelper htmlHelper, string name, string text, object htmlAttributes)
{
RouteValueDictionary attributes =
htmlAttributes == null ? new RouteValueDictionary()
: new RouteValueDictionary(htmlAttributes);
TagBuilder tagBuilder = new TagBuilder("span");
tagBuilder.MergeAttributes(attributes);
tagBuilder.MergeAttribute("name", name, true);
tagBuilder.GenerateId(name);
tagBuilder.SetInnerText(text);
return MvcHtmlString.Create(tagBuilder.ToString());
}
I didn't test this but should be working

Resources