I'm reading percentages from a database, then use that number to create a bar showing visual progress. I need to do something like this on my aspx page:
<%
if (ViewData["width"] != null){
<div style="width: <%: ViewData["width"] %>px;"
</div>
}%>
Of course the above method doesn't work, but hopefully you can see what im trying to achieve. How do i change style attributes dynamically in ASP.NET MVC?
You just wrote HTML in the middle of a code block. You need to put your HTML outside the code block.
<% if (ViewData["width"] != null) { %>
<div style="width: <%: ViewData["width"] %>px;"></div>
<% } %>
Alternatively, you could switch to the Razor language which does away with all the <% %>s and allows you to intersperse C# and HTML much easier. It looks like this:
#if (ViewBag.width != null) {
<div style="width: #(ViewBag.width)px;"></div>
}
Your method should work, you just need to put the div code outside of the server block.
<% if (ViewData["width"] != null){ %>
<div style="width: <%: ViewData["width"] %>px;"
</div>
<% } %>
Related
I am trying to do something somewhat similar to this question. The answer there suggested doing databinding from code-behind, but I have numerous items I'm applying this to and I'd rather not do that if possible.
I have a User Control. A number of images will either be shown or hidden depending on the value of an attribute on the Custom Control. I've tried several different ways of using the <%: ... %> syntax to achieve this but all of them have failed for reasons I'll describe below.
My first try was to do something like the OP on the linked question. From his question:
<select id="myDropDown"
style="width:60px;display:<%# (bool)Eval("ShowDropDown") ? "block" : "none" %>;">
I tried something similar, but like the OP there this didn't replace <%# (bool)Eval("ShowDropDown") ? "block" : "none" %> with a value - it just rendered that as literal text.
The next thing I've tried (and I've tried several variants on this, none of which worked) is the following:
<td id="tdR1Day1" style="vertical-align: top;" runat="server">
<div style="width: 100%; height: 15px">
<img title="Click to add pattern" <%: IsHidden ? "hidden = \"hidden\"" : "" %> align="right" id="imgR1Day1" style="cursor: pointer;" alt="Add" src="../Images/Add.gif">
</div>
</td>
However, this resulted in The Controls collection cannot be modified because the control contains code blocks (i.e. <% ... %>) because I'm trying to dynamically add a div to the td tag from code behind. I'm not directly modifying the img itself, just the td.
When I do the exact same thing on an image that I'm not modifying from code-behind, I get the following HTML, which works exactly how I expect:
<td id="MainContent_scorpio_tdR1Day3" style="vertical-align: top;">
<div style="width: 100%; height: 15px">
<img hidden = "hidden" title="Click to add pattern" align="right" id="imgR1Day3" style="cursor: pointer;" alt="Add" src="../Images/Add.gif">
</div>
</td>
My questions, then:
When I tried doing this as part of CSS, why did it render it as literal text instead of replacing <%: ... %> with a value?
Is there a way around the The Controls collection cannot be modified... exception?
Alternatively, am I just flat-out taking the wrong approach here? For example, should I try to just add this div/image from code-behind like I do with the other div in the td?
There's a couple issues. <%# ... %> is for data binding to a server control. Your <select> is not a server control. Use <%= ... %> which is for a display expression and just call a function. See here for more on inline expressions.
Assuming IsHidden is a boolean variable you can do this:
<script runat="server">
protected string Display()
{
if (IsHidden) {
return "hidden";
}
return "show";
}
</script>
<select id="myDropDown" style='display:<%= Display %>'>
<option>
Test
</option>
</select>
I would also suggest just using a CSS class as well for that. So something like more like
<style>
.hidden {display:none;}
.show {display:block;}
</style>
<script runat="server">
protected string Display()
{
if (IsHidden) {
return "hidden";
}
return "show";
}
</script>
<select id="myDropDown" class="<%= Display %>">
<option>
Test
</option>
</select>
But if you want to modify your table row in the code behind then you should indeed use the data binding inline expression e.g. <%# ... %> and still do the rest the same. This will solve your Controls collection exception.
I have a MVC2 Project using ADO.NET Entity Data Model that I used to generate my view automatically since it has tons of fields. It gave me code like this.
<% using (Html.BeginForm()) {%>
<%= Html.ValidationSummary(true) %>
<div class="editor-label">
<%= Html.LabelFor(model => model.Position) %>
</div>
<div class="editor-field">
<%= Html.TextBoxFor(model => model.Position) %>
<%= Html.ValidationMessageFor(model => model.Position) %>
</div>
But with a ton more fields.
Here is my Controller code:
MyProjectEntities_Career_Applications dbca = new MyProjectEntities_Career_Applications();
[HttpPost]
public ActionResult Apply(Career_Applications application)
{
if (ModelState.IsValid)
{
//save form
dbca.AddToCareer_Applications(application);
dbca.SaveChanges();
}
else
{
ModelState.AddModelError("", "Application could not be submitted. Please correct the errors below.");
}
//redirect to thank you page
return View("Apply", application);
}
When the ModelState.IsValid fails I see the <%= Html.ValidationSummary(true) %> but none of the Html.ValidationMessageFor's ever show up.
What am I missing?
Turns out the problem was with the CSS. Stupid mistake, ugh!
Thanks for the help regardless.
I think you're missing a Jquery reference or error handling library that you're using.
This also happens often when you include validation script multiple times. (In shared view, and in your view)
I have a key in web.config as -
<add key="IsDemo" value ="true"/>
I want to show/hide markup based on above web.config entry for a non-server html tag without using code behind file (as there is no .cs file and there are no runat=server controls).
Something similar to following pseudo code:
IF ( IsDemo == "true" )
THEN
<tr>
<td id="tdDemoSection" colspan="2" align="left" valign="top">
<.....>
</td>
</tr>
ENDIF
Does anyone know that we can write such conditional logic in .aspx markup?
Please help!!!
EDIT:
Section I'm hiding or showing have some data like username and password. So, I do not want user to use Firebug or Web Developer Tools to see hidden markup. markup should not go to client side.
The syntax for something like that would be
<% if(System.Configuration.ConfigurationManager.AppSettings["IsDemo"] == "true") %>
<% { %>
<!-- Protected HTML goes here -->
<% } %>
This assumes that the page is in C#.
You can firm this code up by being more defensive around the AppSettings retrieval e.g. what happens in the case where the value is null etc.
Solution:-
<% If (ConfigurationManager.AppSettings("IsDemo").ToLower().Equals("true")) Then%>
<tr>
<.....>
</tr>
<% Else%>
<tr>
<.....>
</tr>
<% End If%>
If I understand it right, you don't want to use server-side (aspx components, with runat="server" attribute) and just want to control display of html on aspx page then try this solution.
Create a property in codebehind file (or better still in some other config helper class):
//IN C# (OR VB) file
protected string Demo{
get{
return ConfigurationManager.AppSettings["IsDemo"]=="true"?
"none":"block";
}
}
In aspx page:
<tr style="display:<%= Demo%>;">
<td>blah blah</td>
</tr>
I am using ASP.NET MVC2 and to validate the forms i use xVal. It seems like the server side validation works fine, but the client side validation doesnt work or atleast doesn't show up.
The code i use looks like this:
<% using (Html.BeginForm()) {%>
div class="label"><label for="EmailAddress">Email Address</label></div>
<div class="field">
<%= Html.TextBox(Prefix + ".EmailAddress")%>
<%= Html.ValidationMessage(Prefix + ".EmailAddress")%>
</div>
<%}%>
<%= Html.ClientSideValidation<Customer>(Prefix)%>
When i remove the prefix it works fine. But when i remove it only the server side validation works.
Searching on xVal on this side i found this post that looks a bit like the same problem:
Using xval with fields containing periods
But no answers here (yet).
Thanks in advance for the help.
Solved it with the following code:
<% using (Html.BeginForm("ActionName", "Controller")) {%>
div class="label"><label for="EmailAddress">Email Address</label></div>
<div class="field">
<%= Html.TextBox("EmailAddress")%>
<%= Html.ValidationMessage("EmailAddress")%>
</div>
<%}%>
<%= Html.ClientSideValidation<Customer>()%>
I am new to using ASP.NET MVC and I've been having some difficulties with it. I created my model using the Entity Data Model just for the record.
My problem is that I'm trying to insert an image into my MS SQL 2008 server using my new ASP.NET page. The image is a part of the information that I need to store about Employees in my database. From my home HomeController.cs file I right-clicked the Create method and chose to create a view, which it did. However, uploading an image was not part of the auto-generated code.
In the Create View there are a few text-boxes that correspond to my table columns and a single submit button that creates my new database row somehow. I thought that the button would run the code for the other Create method in the HomeController.cs file that takes an Employee as a parameter but I guess my problem lies in the fact that I don't know what happens between me pressing the Submit button and the creation of an Employee object for the Create method.
For reference, here is the code I'm working with .First code for Homecontroller.cs and then code for Create.aspx (note that the variable _db is a copy of my Entity Data Model):
public ActionResult Create()
{
return View();
}
[AcceptVerbs(HttpVerbs.Post)]
public ActionResult Create([Bind(Exclude = "employeeNumber")] Employee employeeToCreate)
{
try
{
_db.AddToEmployee(employeeToCreate);
_db.SaveChanges();
return RedirectToAction("Index");
}
catch
{
return View();
}
}
I don't know why the code above indent's the way it does.
I also don't know why, but the code below doesn't show the first few lines properly so I deleted a few < > around C# code and asp code in order for the code to become visible.(FIXED)
<Page Title="" Language="C#" MasterPageFile="~/Views/Shared/Site.Master" Inherits="System.Web.Mvc.ViewPage<LaunakerfiASP_MVC.Models.Employee>"
<asp:Content ID="Content1" ContentPlaceHolderID="TitleContent" runat="server">
Create
</asp:Content>
<asp:Content ID="Content2" ContentPlaceHolderID="MainContent" runat="server">
<h2>Create</h2>
<%= Html.ValidationSummary("Create was unsuccessful. Please correct the errors and try again.") %>
<% using (Html.BeginForm()) { %>
<fieldset>
<legend>Fields</legend>
<p>
<label for="name">name:</label>
<%= Html.TextBox("name")%>
<%= Html.ValidationMessage("name", "*")%>
</p>
<p>
<label for="email">email:</label>
<%= Html.TextBox("email")%>
<%= Html.ValidationMessage("email", "*")%>
</p>
<p>
<label for="department">department:</label>
<%= Html.TextBox("department")%>
<%= Html.ValidationMessage("department", "*")%>
</p>
<p>
<input type="submit" value="Create" />
</p>
</fieldset>
<% } %>
<div>
<%=Html.ActionLink("Back to List", "Index") %>
</div>
</asp:Content>
So what I would like to do is to add an element to the Create.aspx view that let's me upload an image to the column 'picture' in the table 'Employee'.
In your controller action, you can access the uploaded files through Request.Files
Here are some links about file uploads in ASP.NET MVC :
http://www.hanselman.com/blog/ABackToBasicsCaseStudyImplementingHTTPFileUploadWithASPNETMVCIncludingTestsAndMocks.aspx
http://aspzone.com/tech/asp-net-mvc-file-upload/