html.actionlink take C# variable as parameter - asp.net-mvc

<% foreach (var item in Model) { %>
<table width="100%" class="topicContainer">
<tr>
<td> <%: Html.DisplayFor(modelItem => item.headerclob) %></td>
</tr>
<tr>
<td><%: Html.ActionLink("ViewTopic", "ViewTopic","Forum" ,
new { id=item.topicId },null) %></td>
</tr>
</table>
<% } %>
I want of link ViewTopic item.headerclob should be displayed in hyperlink without using Razor.
I also want to apply css to it.

I think the below code should work
<%: Html.ActionLink("item.headerclob, "ViewTopic","Forum" ,
new { id=item.topicId },null) %>
it use the following format
public static string ActionLink(this HtmlHelper htmlHelper,
string linkText,
string actionName,
string controllerName,
object values,
object htmlAttributes)
if you are using MVC 3 then the you can just use "item.topicId" instead of "id = item.topicId"
Edited
yes it works but after removing semicolon from item.headerClob
<%: Html.ActionLink(item.headerclob, "ViewTopic","Forum" ,
new { id=item.topicId },null) %>
Edit
add a class to action link then use your css file for setting necessary properties
<%: Html.ActionLink(item.headerclob, "ViewTopic","Forum" ,
new { id=item.topicId , #class = "YourClass"},null) %>
now you can apply css properties to the action link you set css properties to others
EDIT
If you do not want to use razor, I could suggest you to build anchors by your self like following
item.headerclob

Related

Pass data to partial class

I am trying to pass a model to my partial class in asp.net however it keeps giving me the following error:
I tried calling the partial class the following ways:
<section id="categoryPartial">
#*1*# #Html.Partial("_CategoryPartial", new EindopdrServer.Models.Category())
#*2*# #Html.Partial("_CategoryPartial", new EindopdrServer.Models.Category{ Name => Model.Name })
#*3*# #Html.RenderPartial("_CategoryPartial", new EindopdrServer.Models.Category { Name => Model.Name })
</section>
My partial class:
#model IEnumerable<EindopdrServer.Models.Category>
<table>
<tr>
#if(Model != null){
#foreach (var item in Model) {
<td class="categoryPartial">
<b>#Html.DisplayFor(modelItem => item.Name)</b>
</td>
}
}
</tr>
</table>
Any solutions?
After removing the # and if statement:
Because the if-statement is code, and not markup, the foreach is already considered code. You don't need to have # before it.
So, simply remove the # character before the foreach

ASP.NET MVC FormCollection TextArea

I have a textarea that represents a description field. The descriptions have commas so when trying to split the field's descriptions the data is not parsed correctly. How can I get each row's description correctly.
var DescList = FormValues["Item.Description"].Split(',').Select(item => item).ToList<string>();
//will not work for obvious reasons. Comma delimited FormCollection has commas to identify separate row data.
It seems like Microsoft designed the FormsCollection without the textarea control in mind. A text area with commas will not work when trying to access each value. What is interesting is that the _entriestables property has it in the perfect format but they chose to make it a private property. Very frustrating.
`
Here is the important part of my viewmodel.
public class TenantViewModel
{
public Tenant Tenant { get; set; }
public Site Site { get; set; }
}
My view is populated like this:
if (Model != null && Model.Tenant != null && Model.Tenant.Site != null && Model.Tenant.Site.Count() > 0)
{<div class="detailsbox_view">
<table id="tblTenantSites">
<tr>
<th>#Html.LabelFor(item => item.Site.Title)</th>
<th>#Html.LabelFor(item => item.Site.Description)</th>
</tr>
#foreach (var Item in Model.Tenant.Sites)
{
<tr>
#Html.HiddenFor(modelItem => Item.SiteId)
<td>
#Html.EditorFor(modelItem => Item.Title)
</td>
<td>
#Html.TextAreaFor(modelItem => Item.Description, new {#width="400" })
</td>
</tr> }
</table>
As you see this site table is a child of Tenant object. This child record does not get automatically updated using this method but the Tenant data does automatically get updated. This is the reason I tried the FormColelction instead.
Is there something I am missing to make this work?
try with this useful function
ValueProviderResult Match=FormCollection.GetValue("ValueProvider");
When you have multiple fields with the same name attribute, they'll come back into your FormCollection as an array. So upon posting a view like this:
<form action="/Home/MyAction">
<textarea id="row_one_description" name="description">
First row's description
</textarea>
<textarea id="row_two_description" name="description">
Second row's description
</textarea>
<input type="submit" value="Submit" />
</form>
you could do something like this in your action
[HttpPost]
public ActionResult MyAction(FormCollection collection)
{
var descriptionArray = collection["description"];
string firstRowDescription = descriptionArray[0];
string secondRowDescription = descriptionArray[1];
}
I must note that this is not the recommended way of dealing with posted data. You should instead be building your view using data from a view model and using strongly typed html helpers to render your controls. That way when you post, your action can take the ViewModel as a parameter. Its properties will be automatically bound and you will have a nice object to play with.
[HttpPost]
public ActionResult MyAction(MyViewModel viewModel)
{
foreach (var row in viewModel.Rows)
{
string description = row.Description;
}
}
EDIT
I'm still assuming a lot about your ViewModel but perhaps try this:
<table id="tblTenantSites">
<tr>
<th>#Html.LabelFor(model => model.Site.Title)</th>
<th>#Html.LabelFor(model => model.Site.Description)</th>
</tr>
#for (var i = i < Model.Tenants.Sites.Count(); i++) {
<tr>
#Html.HiddenFor(model => model.Tenants.Sites[i].SiteId)
<td>
#Html.EditorFor(model => model.Tenants.Sites[i].Title)
</td>
<td>
#Html.TextAreaFor(model => model.Tenants.Sites[i].Description, new { #width="400" } )
</td>
</tr>
}
</table>
You could also try ,
string Match=FormCollection.GetValue("ValueProvider").AttemptedValue;

How to display edit and details on a single view in mvc

I am looking for a partially edit my model - the scenario is i want to display 5 fields and ,2 fields should be editable, and when post happens it should update the editable fields, Strongly type view provide either fully editable view or detail view , how can i have both in conjunction . Any advice or help will be appreciated.
<tr><td>Booking ID</td><td><%: Model.ID %></td></tr>
<tr><td>Transaction No.</td><td><%: Model.TransactionNumber %> (<%: Model.PaymentProvider %>)</td></tr>
<tr><td>Date</td><td><%: String.Format("{0:g}", Model.DateAdded) %></td></tr>
<tr><td>Name</td><td><%: ViewBag.account.FirstName %> <%: ViewBag.account.LastName %></td></tr>
<tr>
<td>
<div class="editor-label">
<%: Html.Label("Event") %>
</div>
</td>
<td>
<div class="editor-field">
<%: Model.Event.Name %><%: Model.Event.Description %>
</div>
</td>
</tr>
<tr><td valign="top">Address</td><td><%= HtmlFormatting.FormatAddress(ViewBag.address)%></td></tr>
<tr><td>Cost</td><td>£<%: String.Format("{0:F}", Model.Cost) %></td></tr>
<tr><td>Status</td><td><%: ViewBag.status %></td></tr>
Thnx
Your implementation is all wrong here. First of all, don't use <table>'s everywhere for layout, you can use the MVC template, just float the div tags left.
You need a ViewModel within which you can reference your Booking object which I assume is a database object?
Something like...
public class BookingViewModel
{
public Booking Booking { get; set; }
}
And when you call your View from your controller pass it in
public ActionResult Index()
{
return View(new BookingViewModel());
}
Then you can add a Post action result to your controller within which you can update your properties
[HttpPost]
public ActionResult Index(BookingViewModel model)
{
//Update your properties
return View(model);
}

Asp.net mvc 2 templates without prefix

Given following view model:
class DetailsViewModel
{
public HeaderViewModel Header {get;set;}
public FooterViewModel Footer {get;set;}
}
I'm using editor template for Header view model:
<%: Html.EditorFor(x => x.Header) %>
The editor template (EditorTemplates/HeaderViewModel.ascx)
<%# Control Language="C#" Inherits="System.Web.Mvc.ViewUserControl<HeaderViewModel>" %>
<% ViewData.TemplateInfo.HtmlFieldPrefix = ""; %>
<%: Html.EditorFor(x => x.Search) %>
The result:
<input type="text" value="" name="Search" id="Search" />
If I remove the line
<% ViewData.TemplateInfo.HtmlFieldPrefix = ""; %>
the result is:
<input type="text" value="" name="Header.Search" id="Header_Search" />
Is there another way to achieve the same - render the names of the control without prefix?
I was thinking about a helper:
public static MvcHtmlString EditorWithoutPrefix<TModel, TValue>(
this HtmlHelper<TModel> html, TValue value)
{
var htmlHelper =... // create new HtmlHelper<TValue> and set it's model to be 'value' argument
return htmlHelper.EditorForModel();
}
and use it:
<%: Html.EditorWithoutPrefix(Model.Header) %>
but it is throwing exceptions.
Or maybe you know another elegant way to render names without prefix?
You could use the proper overload:
<%: Html.EditorFor(x => x.Search, "SearchViewModel", "") %>

asp.net mvc posting strongly typed passes null?

I'm running into an issue when posting a form back from different views... I'm using the same form and it will work in one view, but not the other. When it errors in the post, the parameter will pass as null. This is my form:
<% using (Html.BeginForm()) { %>
<table>
<tr>
<td colspan="4" style="line-height:20px;"><label for="Search.searchString">Search</label></td>
</tr>
<tr>
<td><%= Html.TextBox("Search.searchString") %>
</td>
<td><label for="Search.category"><nobr>In Category</nobr></label></td>
<td><%= Html.TextBox("Search.category") %></td>
<td><input type="submit" value="Search" /></td>
</tr>
</table>
<% } %>
I have 2 views... an Index and a Search view. When I post this form from the index view, it works fine. When I post it from the search view, it tells me that my Search object is null. This is my post method:
[AcceptVerbs(HttpVerbs.Post)]
public ActionResult Index(Search search)
{
if (String.IsNullOrEmpty(search.searchString))
search.searchString = "all";
return RedirectToRoute("search", new RouteValueDictionary { { "search", search.searchString }, { "category", search.category } });
}
The post methods for both index and search are the same, so I'm rather confused as to why one works while the other doesn't. Any thoughts? Thanks for the help!
Does your second view inherit from your search object or does the model for the view inherit from the search object?
So your Index view <namespace.SearchObject>
and your Search <namespace.SearchObject>
Of if search inherits from <namespace.SearchView> then your SearchView must inherit from SearchObject.
It's because your ActionResult method has the same name as the typed model your passing in.
Try using the ActionName attribute:
[ActionName("Search"), AcceptVerbs(HttpVerbs.Post)]
public ActionResult DoSearch(Search search)
{
return View();
}
Ok, I think I have this figured out.... I ended up modifying the html.beginform tag to the following...
using (Html.BeginForm("Index", "Home"))
and forced it to always use the index post method, and it works. Is this the best way to fix it though?

Resources