Html.RouteLink busted? - asp.net-mvc

Why does this code produce these results?
CODE:
<%# Control Language="C#"
Inherits="System.Web.Mvc.ViewUserControl< RoomsAlive.ViewModels.ProductCatalogViewModel >" %>
<div id="product_nav">
<ul>
<%--ADD PREV TAB--%>
<% if (Model.HasPreviousPage) %>
<% { %>
<li><%= Html.RouteLink("<<", "CatalogMenu", new { controller = "Catalog", action = "Index", style = (Model.GroupName), position = (Model.PageIndex - 1) })%></li>
<% } %>
<%--LOOP HERE--%>
<% foreach (RoomsAlive.Models.ProductMenuView myFPV in Model.ProductMenu)
{ %>
<li><%= Html.RouteLink(myFPV.Name, "CatalogMenu", new { controller = "Catalog", action = "Index", group = Model.GroupName })%></li>
<% } %>
<%--ADD NEXT TAB--%>
<% if (Model.HasNextPage) %>
<% { %>
<li><%= Html.RouteLink(">>", "CatalogMenu", new { controller = "Catalog", action = "Index", position = (Model.PageIndex + 1) })%></li>
<% } %>
</ul>
</div>
RESULTS:
<div id="product_nav">
<ul>
<li>LifeStyle</li>
<li>Rooms</li>
</ul>
</div>
BTW: If I use the <% %> form instead of the <%= %> form it produces this:
<div id="product_nav">
<ul>
<li></li>
<li></li>
</ul>
</div>

Why are you specifying the controller and action in the object part of the Actionlink?
Wouldn't it be best to do it this way:
<%= Html.RouteLink("<<", "Index", "Catalog", new { style = Model.GroupName, position = (Model.PageIndex - 1) }, null)%>
The second property of ActionLink is always the desired action name, and you are setting it to CatalogMenu, but then you're then creating an object that says "Index". For this reason (as I have no idea what you want 'CatalogMenu' to be), I have taken it out.
Please also note the null after the routeValues object. This is because the 10 constructors for Html.ActionLink, this one fits the best:
ActionLink(LinkText, ActionName, ControllerName, RouteValues, HtmlAttributes)
Also, if you use <% ... %> instead of <%= ... %>, then it will not output the link. This is because the ActionLink returns a string. All the '=' does in the tag is effectively a Response.Write.
Hope this explains it.

Related

Passing SelectList through ViewData to editor templates - not displayed properly

It's a bit complicated so bear with me.
Let's say I've got an example of a controller edit action defined like:
Node nd = _repo.getNode(id);
List<Category> ac = new List<Category>();
ac.AddRange(_repo.getCategories());
SelectList acl = new SelectList(ac, "category_id", "category_name", ac.Where(cat => cat.category_id == nd.category_id).First());
ViewData["category_id"] = acl;
return View(nd);
The view is templated like so:
<%# Control Language="C#" Inherits="System.Web.Mvc.ViewUserControl<Myapp.Models.Node>" %>
<% if (ViewData.TemplateInfo.TemplateDepth > 1)
{ %>
<%= ViewData.ModelMetadata.SimpleDisplayText %>
<% }
else
{ %>
<table cellpadding="0" cellspacing="0" border="0">
<% foreach (var prop in ViewData.ModelMetadata.Properties.Where(pm => pm.ShowForEdit && !ViewData.TemplateInfo.Visited(pm)))
{ %>
<% if (prop.HideSurroundingHtml)
{ %>
<%= Html.Editor(prop.PropertyName) %>
<% }
else
{ %>
<tr>
<td>
<div class="editor-label" style="text-align: right;">
<%= prop.IsRequired ? "*" : ""%>
<%= Html.Label(prop.PropertyName)%>
</div>
</td>
<td>
<div class="editor-field">
<% if (ViewData.Keys.Contains(prop.PropertyName))
{
if ((ViewData[prop.PropertyName]).GetType().Name == "SelectList")
{ %>
<%= Html.DropDownList(prop.PropertyName, (SelectList)ViewData[prop.PropertyName])%>
<% }
else
{ %>
<%= Html.Editor(prop.PropertyName)%>
<% } %>
<% }
else
{ %>
<%= Html.Editor(prop.PropertyName)%>
<% } %>
<%= Html.ValidationMessage(prop.PropertyName, "*")%>
</div>
</td>
</tr>
<% } %>
<% } %>
</table>
<% } %>
So, what the template does is display a dropdown list for every property for which ViewData["property_name"] exists.
I've also defined DisplayName metadata attributes for every property of my Node class.
Now, the dropdown lists display fine and are being populated correctly, but:
The first value from a list is always selected, even though the SelectList selected value predicate is fine and does set a proper value (in the debugger at least).
Html.Label in the template returns a proper DisplayName for properties, but when I define a ViewData for them so as to display the dropdown list, the label resets to normal property name (ie. category_id instead of Category).
What gives? Can you think of any "neater" way to accomplish this functionality?
Allright, no one's answering so there's my answer, maybe it comes in handy for someone:
Do not use your property names for ViewData keys! It messes up with the view model, so your views get confused and start to behave strangely.
Actually, best avoid the magic strings mess entirely, but if you insist, just use something like ex.: ViewData[prop.PropertyName+"_list"]. Your views are going to be fine now.

ajax.beginform inside a for loop

so I am using a foreach loop to iterate through comments. The comment section is wrapped inside "Comments" div. My function DeleteComment fetches comments again once you delete a comment and rebinds it to the control. However, after you delete a comment, anytime you try to delete another comment, the commentId of the very first deleted comment would keep getting passed to DeleteComment function instead of the passing the commentId of the comment you are trying to delete. If you refresh the page, then you can delete ONE comment again, and the same problem if you try to delete another.
<table>
<% foreach (var item in Model) { %>
<tr> <td>item.Comment </td>
<td>
<%if (HttpContext.Current.User.Identity.IsAuthenticated && item.Poster.UserName == HttpContext.Current.User.Identity.Name)
{ %>
<%using (Ajax.BeginForm("DeleteComment", "Home", new AjaxOptions {UpdateTargetId = "Comments"}))
{%>
<%=Html.Hidden("articleId", item.CarrierId) %>
<%=Html.Hidden("num_comments", (int)ViewData["num_comments"]) %>
<%=Html.Hidden("commentId", item.CommentId) %>
<input type = "submit" value = "delete" />
<%} %>
<%} %>
</td>
</tr>
<table>
For example, you delete comment with commentId 1... then you try to delete some other comment, but commentId 1 would keep getting passed. You refresh the page, problem gone... for one comment...
<div id = "Comments">
<%if ((int)ViewData["num_comments"] > 0)
{ %>
<%Html.RenderPartial("CommentsX", Model.Comments, new ViewDataDictionary{{"num_comments", ViewData["num_comments"] }}); %>
<%} %>
</div>
where CommentsX is the ascx control that contains the for loop code I posted above.
Sometimes having multiple elements on the same page with the same ids can cause funky results like you are seeing. Try making the id's unique like below:
<table>
<% int index=1;
foreach (var item in Model) { %>
<tr> <td>item.Comment </td>
<td>
<%if (HttpContext.Current.User.Identity.IsAuthenticated && item.Poster.UserName == HttpContext.Current.User.Identity.Name)
{ %>
<%using (Ajax.BeginForm("DeleteComment", "Home", new AjaxOptions {UpdateTargetId = "Comments"}))
{%>
<%=Html.Hidden("articleId" + index, item.CarrierId) %>
<%=Html.Hidden("num_comments" + index, (int)ViewData["num_comments"]) %>
<%=Html.Hidden("commentId" + index, item.CommentId) %>
<input type = "submit" value = "delete" />
<%} %>
<% index++;
} %>
</td>
</tr>
<table>

Proper submission of forms with autogenerated controls

Based on:
MVC Html.CheckBox and form submit issue
Let's consider following example. View:
<% using(Html.BeginForm("Retrieve", "Home")) %>
<% { %>
<%foreach (var app in newApps) { %>
<tr>
<td><%=Html.CheckBox(""+app.ApplicationId )%></td>
</tr>
<%} %>
<input type"submit"/>
<% } %>
Controller:
List<app>=newApps; //Database bind
for(int i=0; i<app.Count;i++)
{
var checkbox=Request.Form[""+app[i].ApplicationId];
if(checkbox!="false")// if not false then true,false is returned
}
Proposed solution was about manual parsing of Request.Form that seems for me out of MVC concept. It makes the problem while unit testing of this controller method. In this case I need to generate mock Request.Form object instead of some ViewModel passed as input param.
Q: Is there some other solution of submitting forms like this, so that ViewModel object, containing collection of submitted controls, passed as input param to controller method?
For example:
[AcceptVerbs(HttpVerbs.Post)]
public ActionResult Retrieve(AppList[] applist)
or
public ActionResult Retrieve(AppList<App> applist)
etc
Controller:
[AcceptVerbs(HttpVerbs.Post)]
public ActionResult Retrieve(AppList[] applist)
View:
<% using(Html.BeginForm("Retrieve", "Home")) %> { %>
<%foreach (var app in newApps) { %>
<tr>
<td><%=Html.CheckBox(String.Format("appList[{0}].AProperty", app.ApplicationId) %></td>
</tr>
<% } %>
<input type"submit" />
<% } %>
Read this: Scott Hanselman's ComputerZen.com - ASP.NET Wire Format for Model Binding to Arrays, Lists, Collections, Dictionaries
UPDATED:
If ApplicationId is a key from DB it is better to use AppList<App> as Action parameter. Then your form would be looking as:
<% using(Html.BeginForm("Retrieve", "Home")) %> { %>
<% var counter = 0; %>
<% foreach (var app in newApps) { %>
<tr>
<td><%=Html.CheckBox(String.Format("appList[{0}].Key", counter), app.ApplicationId) %></td>
<!-- ... -->
<td><%=Html.Input(String.Format("appList[{0}].Value.SomeProperty1", counter), app.SomeProperty1) %></td>
<td><%=Html.Input(String.Format("appList[{0}].Value.SomePropertyN", counter), app.SomePropertyN) %></td>
<% counter = counter + 1; %>
</tr>
<% } %>
<input type"submit" />
<% } %>

MVC - Displaying Content

How to Display the following
public ActionResult Index()
{
IEnumerable<int> items = Enumerable.Range(1000, 5);
ViewData["Collection"] = items;
return View();
}
in "View"
<ul>
<% foreach(int i in (IEnumerable)ViewData["Collection"]){ %>
<li>
<% =i.ToString(); }%>
</li>
</ul>
the foreach throws System.Web.HttpCompileException.
You had the closing brace of the foreach's loop in the wrong place. This is what you need:
<ul>
<% foreach (int i in (IEnumerable)ViewData["Collection"]) { %>
<li>
<%= i.ToString() %>
</li>
<% } %>
</ul>
And you also had some other extra punctuation in there as well (such as an extra semicolon).

ASP.NET MVC Passing Data from View to Controller

I have a view with a grid that contains items added to a workstation. The user can select an item from a drop down list and click an action link which calls a controller that adds that item to the workstation. I can make it work by reading the FormCollection object in the Post action of the controller.
<p>
<% using(Html.BeginForm("AddItem", "Home")) { %>
<label for="ItemID">Item:</label>
<%= Html.DropDownList("ItemID", Model.ItemsList) %>
<%= Html.Hidden("WorkstationID", Model.Workstation.RecordID) %>
<input type="submit" value="Submit" />
<% } %>
</p>
[AcceptVerbs(HttpVerbs.Post)]
public ActionResult AddItem(FormCollection formValue)
{
long workstationId = Convert.ToInt64(formValue["WorkstationID"]);
long itemId = Convert.ToInt64(formValue["ItemID"]);
Workstation workstation = itilRepository.FindWorkstation(workstationId);
Item item = itilRepository.FindItem(itemId);
itilRepository.AddItem(workstation, item);
itilRepository.Save();
return Content("Item added successfully!");
}
What I want to do is be able to submit the two parameters the workstationId and itemId to the controller using Ajax.ActionLink and have the new item that was added get inserted into the grid. I am rendering the grid like this:
<table>
<tr>
<th></th>
<th>
Name
</th>
<th>
Service Tag
</th>
<th>
Serial Number
</th>
</tr>
<% foreach (var item in Model.Items) { %>
<tr>
<td>
<%= Html.ActionLink("Edit", "ItemEdit", new { id = item.RecordID }) %> |
<%= Html.ActionLink("Details", "ItemDetails", new { id = item.RecordID })%>
</td>
<td>
<%= Html.Encode(item.Name) %>
</td>
<td>
<%= Html.Encode(item.ServiceTag) %>
</td>
<td>
<%= Html.Encode(item.SerialNumber) %>
</td>
</tr>
<% } %>
</table>
The problem I have is when I submit using the ActionLink I can't figure out how to pass in the parameters to the controller and how to update the grid without reloading the entire view.
I would really appreciate some help with this or even a link to a tutorials that does something similar.
Thank You!
This is the working version, the one problem is that when the controller returns the partial view that is all that gets rendred the actual page is gone.
<% using (Ajax.BeginForm("AddItem", null,
new AjaxOptions
{
UpdateTargetId = "ResultsGoHere",
InsertionMode = InsertionMode.Replace
},
new { #id = "itemForm" } ))
{ %>
<label for="ItemID">Item:</label>
<%= Html.DropDownList("itemId", Model.ItemsList) %>
<%= Html.Hidden("workstationId", Model.Workstation.RecordID) %>
Submit
<div id="ResultsGoHere">
<% Html.RenderPartial("WorkstationItems", Model.Items); %>
</div>
<% } %>
Not sure what the cause is, the replace was working correctly before but the controller wasn't getting the drop down value. Now the controller is getting the value but the partial view that is returned replaces the entire page.
The Action Method:
[AcceptVerbs(HttpVerbs.Post)]
public ActionResult AddItem(string workstationId, string itemId)
{
long lworkstationId = Convert.ToInt64(workstationId);
long litemId = Convert.ToInt64(itemId);
Workstation workstation = itilRepository.FindWorkstation(lworkstationId);
Item item = itilRepository.FindItem(litemId);
IQueryable<Item> items = itilRepository.AddItem(workstation, item);
itilRepository.Save();
return PartialView("WorkstationItems", items);
}
This is the HTML for the View that does all the work:
<%# Page Title="" Language="C#" MasterPageFile="~/Views/Shared/Site.Master" Inherits="System.Web.Mvc.ViewPage<ITILDatabase.Models.WorkstationFormViewModel>" %>
<asp:Content ID="Content1" ContentPlaceHolderID="TitleContent" runat="server">
Workstation Details
</asp:Content>
<asp:Content ID="Content2" ContentPlaceHolderID="MainContent" runat="server">
<script src="/Scripts/MicrosoftAjax.js" type="text/javascript"></script>
<script src="/Scripts/MicrosoftMvcAjax.js" type="text/javascript"></script>
<link type="text/css" href="/../Content/css/ui-lightness/jquery-ui-1.7.2.custom.css" rel="stylesheet" />
<script type="text/javascript" src="/../Content/js/jquery-1.3.2.min.js"></script>
<script type="text/javascript" src="/../Content/js/jquery-ui-1.7.2.custom.min.js"></script>
<h2>
Workstation Details</h2>
<fieldset>
<legend>Fields</legend>
<p>
Record ID:
<%= Html.Encode(Model.Workstation.RecordID) %>
</p>
<p>
Name:
<%= Html.Encode(Model.Workstation.Name) %>
</p>
<p>
Description:
<%= Html.Encode(Model.Workstation.Description) %>
</p>
<p>
Site:
<%= Html.Encode(Model.Workstation.Site.Name) %>
</p>
<p>
Modified By:
<%= Html.Encode(Model.Workstation.ModifiedBy) %>
</p>
<p>
Modified On:
<%= Html.Encode(String.Format("{0:g}", Model.Workstation.ModifiedOn)) %>
</p>
<p>
Created By:
<%= Html.Encode(Model.Workstation.CreatedBy) %>
</p>
<p>
Created On:
<%= Html.Encode(String.Format("{0:g}", Model.Workstation.CreatedOn)) %>
</p>
</fieldset>
<fieldset>
<legend>People</legend>
<% Html.RenderPartial("WorkstationPeople", Model.People); %>
</fieldset>
<fieldset>
<legend>Positions</legend>
<% Html.RenderPartial("WorkstationPositions", Model.Positions); %>
</fieldset>
<fieldset>
<legend>Items</legend>
<% using (Ajax.BeginForm("AddItem", "Home", null,
new AjaxOptions
{
UpdateTargetId = "ResultsGoHere",
InsertionMode = InsertionMode.Replace
},
new { #id = "itemForm" } ))
{ %>
<label for="ItemID">Item:</label>
<%= Html.DropDownList("itemId", Model.ItemsList) %>
<%= Html.Hidden("workstationId", Model.Workstation.RecordID) %>
Submit
<div id="ResultsGoHere">
<% Html.RenderPartial("WorkstationItems", Model.Items); %>
</div>
<% } %>
</fieldset>
<br />
<p>
<%=Html.ActionLink("Edit", "WorkstationEdit", new { id = Model.Workstation.RecordID }) %>
|
<%=Html.ActionLink("Back to List", "Index") %>
</p>
</asp:Content>
What result are you expecting from the AJAX call?
You could use the AjaxHelper object's helper methods instead of the HtmlHelper to render the link. For example, to get new content with an AJAX HttpPOST call and insert it into a <div> with the id set to ResultsGoHere you render the following link:
<%= Ajax.ActionLink("Edit", "ItemEdit",
new {
itemId = item.RecordId,
workstationId = myWorkStationId
},
new AjaxOptions {
HttpMethod="POST",
UpdateTargetId="ResultsGoHere",
InsertionMode = InsertionMode.Replace
}) %>
In your AcionMethod, you can simply test on Request.IsAjaxRequest() to decide what to return:
[AcceptVerbs(HttpVerbs.Post)]
public ActionResult ItemEdit(string itemId, string workstationId) {
// edit the item and get it back
if (Request.IsAjaxRequest()) {
return PartialView("SingleItem", item);
}
return RedirectToAction("ItemEdit", new { itemId = item.RecordId, workstationId = workstationId });
}
// fallback for get requests
public ActionResult ItemEdit(string itemId, string workstationId)
{
// do stuff and return view
}
This is how you could do it using the Ajax.BeginForm() method instead:
<% using (Ajax.BeginForm("ItemEdit", null, new AjaxOptions
{
UpdateTargetId = "ResultsGoHere",
InsertionMode = InsertionMode.Replace
}, new { #id = "itemForm" } )
{ %>
<p>
<%= Html.DropDownList("itemId") %></p>
<p>
<%= Html.DropDownList("workstationId") %></p>
<p>
Submit
</p>
<% } %>
Please note that the code is in its current state in no way fully functional - the dropdownlists don't get their items from anywhere, there is no <div> to take care of the results from the AJAX request, and the onclick attribute on the link that submits the form requires that jQuery is included (in which case it is way better to give the link an id and add a click() event handler to it from a separate js file...)
EDIT: Oh, and I haven't verified that it is OK to pass a null value to the routeValues parameter. If not, just supply the controller and action names, and you'll be fine.
how can you pass the model from the view to the post create action of the controller using ajax.actionlink?
Here, as of my knowledge, we can pass data from View to Controller in two ways...
Using Formcollection built in keyword like this..
[HttpPost]
public string filter(FormCollection fc)
{
return "welcome to filtering : "+fc[0];
(or)
return "welcome to filtering : "+fc["here id of the control in view"];
}
FormCollection will work only when you click any button inside a form. In other cases it contains only empty data
Using model class
[HttpPost]
public string filter(classname cn)
{
return "welcome to filtering : "+cn.Empid+""+cn.Empname;
}
This is how you will be able to send multiple parameters through actionLink.
For this situation please refer to the code below:
#Html.ActionLink("Link text", "Action Name", null, routeValues: new { pram_serviceLine = Model.ServiceLine_ID, pram_Month = Model.Month, pram_Year = Model.Year, flag = "ROTATION" }
Reply if it works.

Resources