Asp.net Mvc1
On my Views/home/Index.aspx which routes from http://localhost/DefectSeverityAssessmentMvcBeta/
This renders
Response.Write("<a href=\"");
Response.Write(Url.Action("Create", "Registration"));
Response.Write("\">Begin Registration</a>");
But returns a 404 for the address of the link http://localhost/DefectSeverityAssessmentMvcBeta/Registration/Create
while this Does not render or show in view source but doesn't cause any exception:
Html.ActionLink("Begin Registration", "Create", "Registration");
I have a RegistrationController and a /Views/Registration/Create.aspx
The registration controller has breakpoints on Index() and Create() but they are not being hit.
I'm not sure how I would use <%= %> in this scenario because it's inside the following code block:
<% if (ViewData.ContainsKey("user"))
{
if (ViewData.ContainsKey("registered") && (bool)ViewData["registered"] == true)
{
//Html.RouteLink("Resume Assessment", "Assessment", new { controller = "Assessment", action = "Index" });
Response.Write("<a href=\"");
// Html.ActionLink("Resume Assessment", "Index", "Assessment");
Response.Write("\">Resume Assessment</a>");
}
else
{
//Html.RouteLink("Begin", "Registration", new { controller = "Registration", action = "Edit" });
// Html.ActionLink("Begin Registration", "Create", "Registration");
Html.RouteLink("Begin", "Default", new { controller = "Registration", action = "Edit" });
//Response.Write("<a href=\"");
//Response.Write(Url.Action("Create", "Registration"));
//Response.Write("\">Begin Registration</a>");
}
}
else
{ Response.Write("Authentication failed"); }
%>
Are you using <% %> in the HTML for both Response.Write and Html.ActionLink? Try using <%= %> for Html.ActionLink(...);
The added equal sign calls Response.Write behind the scenes thus writing you code to the screen.
Because Html.ActionLink return the string and do not write to the response stream. You need to write to your page using <%= %> or Response.Write();
Response.Write(Html.ActionLink("Begin Registration", "Create", "Registration"));
I was not making use of the ability to use
<% if(x) {%> <%=Html.ActionLink(...)%><% } %>
Thanks to Charles Conway I got it working. Here's the code I wound up with:
<div class="entry">
<% if (ViewData.ContainsKey("user"))
{
if (ViewData.ContainsKey("registered") && (bool)ViewData["registered"] == true)
{ %>
<%=Html.ActionLink("Resume Assessment", "Index", "Assessment") %>
<% }
else
{ %> <%=Html.ActionLink("Begin Registration", "Create", "Registration") %>
<%
}
}
else
{ Response.Write("Authentication failed"); }
%></div>
Are you using an equals sign in your context switch, like this?
<%= Html.ActionLink("Begin Registration", "Create", "Registration"); %>
^--needs equals sign here
If you're not using an equals sign, you have to write directly to the Response object.
As far as the routing errors go, you can check out your routes using Phil Haack's diagnostic tool at http://haacked.com/archive/2008/03/13/url-routing-debugger.aspx.
Anything less than IIS7 requires special configuration for the routing.
Related
I'm currently learning rails and working on what I'm sure is everyone's first rails app, a simple todo list. I need to implement a checkbox next to the items to indicate whether they are complete or not. Each item has a boolean attribute called "completed" in their model. I have found a couple checkbox questions while searching but none explain the syntax very easily in the context of the index view.
Also, I really want the checkbox to work without a submit button. I know I could accomplish something like this using AngularJS's ng-model but I don't think it would be practical to implement angular for such a small thing and I don't know how angular works with rails.
If anyone could give me a pointer in the right direction, it would be greatly appreciated. Here's my index.html.erb for reference.
<h1>
To Do List
</h1>
<table>
<tr>
<% #todo_items.each do |item| %>
<!-- Checkbox here -->
<tc style="<%= 'text-decoration: line-through' if item.completed %>">
<%= link_to item.title, item %>
</tc>
<tc>
<%= item.description %>
</tc>
<tc>
<%= link_to "Edit", edit_todo_item_path(item) %>
</tc>
<tc>
<%= link_to "Delete",item, data:{:confirm => "Are you sure you want to delete this item?"}, :method => :delete %>
</tc>
<hr/>
<% end %>
</tr>
</table>
<p>
<%= link_to "Add Item", new_todo_item_path %>
</p>
This is my way, I don't know this way is right direction or not but this works for me (also different case but same of concept).
views for checkbox
You could put an id item or something into attribute of checkbox for find an object in controller if you send data to controller for get record of object, and you could define if attribute completed of record is true or false:
<%= check_box_tag :completed_item, 1, item.completed? ? true : false, { class: 'name-of-class', data: { id: item.id} } %>
controller
You need two action call set_completed and remove_completed, and also you don't need templates for them, just use format as json:
before_action :set_item, only [:set_completed, :remove_completed, :other_action]
def set_completed
#item.set_completed!
respond_to do |format|
format.json { render :json => { :success => true } }
end
end
def remove_completed
#item.remove_completed!
respond_to do |format|
format.json { render :json => { :success => true } }
end
end
private
def set_item
#item = Item.find params[:id]
end
Model
For set_completed! and remove_completed! you could define in your model
def set_default!
self.update_attributes(:completed => true)
end
def remove_default!
self.update_attributes(:completed => false)
end
routes
resources :address do
collection do
post 'set_completed'
post 'remove_completed'
end
end
Also, you need help JavaScript for handle send request from view to controller event click of checkbox:
jQuery
$(".completed_item").click(function(){
var check = $(this).is(":checked");
if (check == true){
set_completed($(this).attr('data-id'));
} else{
remove_completed($(this).attr('data-id'));
}
});
function set_completed(data_id) {
$.ajax({
type: 'POST',
url: "/items/set_completed",
data: { id: data_id},
dataType: 'json',
success: function(response){
if(response){
}else{
alert('error');
}
}
})
}
function remove_compelted(data_id) {
$.ajax({
type: 'POST',
url: "/items/set_completed",
data: { id: data_id},
dataType: 'json',
success: function(response){
if(response){
}else{
alert('error');
}
}
})
}
I have a controller and I need to make a link to my view:
#projeto.atividades.each do |a|
#mapa[:tasks] << {
id:a.id,
name:<%= link_to a.descricao, edit_atividade_path(atividade) %>
}
end
a.descricao = the word that I want to be the link.
edit_atividade_path(atividade) = my view.
What is the syntax?
Please try the following:
#mapa[:tasks] << {
id:a.id,
name: view_context.link_to(a.descricao, edit_atividade_path(atividade))
}
Also a point to remember is that in your controller you don't need the <% or %> scriptlets since its already ruby code.
Hopefully this question is quick and painless
I have a mvc view where i want to display either one of two values depending on an if statement. This is what I have in the view itself:
<%if (model.CountryId == model.CountryId) %>
<%= Html.Encode(model.LocalComment)%>
<%= Html.Encode(model.IntComment)%>
If true display model.LocalComment, if false display model.IntComment.
This doesn't work as I get both values showing. What am I doing wrong?
Your if statement always evaluates to true. You are testing whether model.CountryId equals model.CountryId which is always true: if (model.CountryId == model.CountryId). Also you are missing an else statement. It should be like this:
<%if (model.CountryId == 1) { %>
<%= Html.Encode(model.LocalComment) %>
<% } else if (model.CountryId == 2) { %>
<%= Html.Encode(model.IntComment) %>
<% } %>
Obviously you need to replace 1 and 2 with the proper values.
Personally I would write an HTML helper for this task to avoid the tag soup in the views:
public static MvcHtmlString Comment(this HtmlHelper<YourModelType> htmlHelper)
{
var model = htmlHelper.ViewData.Model;
if (model.CountryId == 1)
{
return MvcHtmlString.Create(model.LocalComment);
}
else if (model.CountryId == 2)
{
return MvcHtmlString.Create(model.IntComment);
}
return MvcHtmlString.Empty;
}
And then in your view simply:
<%= Html.Comment() %>
Aside from Darin's point about the condition always being true, you might want to consider using the conditional operator:
<%= Html.Encode(model.CountryId == 1 ? model.LocalComment : model.IntComment) %>
(Adjust for whatever your real condition would be, of course.)
Personally I find this easier to read than the big mixture of <% %> and <%= %>.
Conditional Rendering in Asp.Net MVC Views
<% if(customer.Type == CustomerType.Affiliate) %>
<%= this.Html.Image("~/Content/Images/customer_affiliate_icon.jpg")%>
<% else if(customer.Type == CustomerType.Preferred) %>
<%= this.Html.Image("~/Content/Images/customer_preferred_icon.jpg")%>
<% else %>
<%= this.Html.Image("~/Content/Images/customer_regular_icon.jpg")%>
Can you help me? I used contoller HomeConrtoller.cs for view, edit and delete articles. All work, but When I go to the next page I get error don't found http://local.../Articles/1
public ActionResult Articles(int? page)
{
var viewData = mybaseRepository.FindAllArticles();
const int pageSize = 10;
var paginatedArticle = new PaginatedList<Article>(viewData, page ?? 0 , pageSize);
ViewData["Page"] = paginatedArticle.PageIndex;
return View(paginatedArticle);
}
In Global.asax.cs
routes.MapRoute(
"Articles",
"Articles/{page}",
new { controller = "Home", action = "Aticles", page = (int?)null }
);
paging in Articles.aspx
<% if (Model.HasPreviousPage) { %>
<%= Html.RouteLink("предыдущая <<<",
"Articles",
new {page = (Model.PageIndex - 1) })%>
<% } %>
<% if (Model.HasNextPage) { %>
<%= Html.RouteLink(">>> следующая",
"Articles",
new {page = (Model.PageIndex + 1) })%>
<% } %>
<div>
You wrote "Articls" in the URL but "Articles" when defining the route. Would that be it?
I am trying to implementation the same pagination that is used in the NerdDinner ASP.NET. I am receiving the following error in my view, whenever the pagination starts to kick in.
"A route named 'Index' could not be
found in the route collection."
The error is happening on Line 64.
Line 62: <% if (this.Model.HasNextPage)
Line 63: { %>
Line 64: <%= this.Html.RouteLink("Next Page >>>", "Index", new { page = (this.Model.PageIndex + 1) })%>
Line 65: <% } %>
Line 66: </div>
My controller code is:
[Authorize]
public ActionResult Index(int? page)
{
const int pageSize = 25;
var topics = this.TopicRepository.FindAllTopics();
var paginatedTopics = new PaginatedList<Topic>(topics, page ?? 0, pageSize);
return this.View(paginatedTopics);
}
My view code is ...
<%# Page Title="" Language="C#" MasterPageFile="~/Views/Shared/Site.Master" Inherits="System.Web.Mvc.ViewPage<CreativeLogic.Sauron.WebMvc.Helpers.PaginatedList<CreativeLogic.Sauron.WebMvc.Models.Topic>>" %>
<!-- Code to display the list here -->
<div class="pagination">
<% if (this.Model.HasPreviousPage)
{ %>
<%= this.Html.RouteLink("<<< Previous Page",
"Index", new { page = (this.Model.PageIndex - 1) }) %>
<% } %>
<% if (this.Model.HasNextPage)
{ %>
<%= this.Html.RouteLink("Next Page >>>",
"Index", new { page = (this.Model.PageIndex + 1) })%>
<% } %>
</div>
This is my first attempt at doing the pagination in ASP.NET MVC ... if there is a better way, please let me know, otherwise, where am I going wrong here?
Thanks much!
You should not use RouteLink (which takes a route name) but instead use an ActionLink which takes an action name like Index.
Well the RouteLink Extension Method looks for a defined route with the name of "Index" in the Global.asax, and by default there is just 1 route defined in the Global the "Default", it looks like this:
routes.MapRoute(
"Default", // Route name
"{controller}/{action}/{id}", // URL with parameters
new { controller = "Home", action = "Index", id = "" } // Parameter defaults
);
Maybe as HakonB said you must use the ActionLink Extension Method or define a route in the Global asax for the pagination.