Html.ValidationMessageFor not showing - c#

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)

Related

MVC Problems 16

I am trying to post a part of my model for a view to action in another controller. I've tried to do it this way:
<% using (Html.BeginForm("Register", "User", new {createDto = Model.UserCreateDto}, FormMethod.Post))
{%>
Form code here...
<%}%>
UserCreateDto is a part of my model and it's being filled in this form. I'm trying to pass it to "Register" action in UsersController:
[HttpPost]
public ActionResult Register(UserCreateDto createDto)
The problem is that route value in Register action is null (createDto) after form submit. Maybe it is happening because route values are being attached to url before form submit event (and before model fields are filled).
Is there any way to do what I want?
UPDATE Here is the actual HTML code:
Имя пользователя
Пароль
E-mail
And here is the updated form code:
<% using (Html.BeginForm("Register", "User", FormMethod.Post))
{%>
<%: Html.HiddenFor(userCreateDto => Model.UserCreateDto.Username) %>
<%: Html.HiddenFor(userCreateDto => Model.UserCreateDto.Password) %>
<%: Html.HiddenFor(userCreateDto => Model.UserCreateDto.Email) %>
<%: Html.HiddenFor(userCreateDto => Model.UserCreateDto.Active) %>
<%= Html.LabeledValidatedTextBoxFor(username => Model.UserCreateDto.Username, true) %>
<%= Html.LabeledValidatedTextBoxFor(password => Model.UserCreateDto.Password, true)%>
<%= Html.LabeledValidatedTextBoxFor(email => Model.UserCreateDto.Email, true)%>
<input type="submit" value="Register"/>
<%}%>
Html.LabeledValidatedTextBoxFor is just my custon HTML helper.
Here is updated action signature:
[HttpPost]
public ActionResult Register(UserCreateDto userCreateDto)
userСreateDto in this action is still null.http://www.media fire.com/file/5dcrv5zupy44c0i/A16.rar/file By the way, is there any way not to use hidden fields? They are not secure enough to pass through them user registration information.
Probably what you're looking for is ModelBinding. If your UserCreateDto Model is complex enough, and by that I mean that it contains any other complex type inside, the DefaultModelBinder is not going to know how to fill your model. So you need to tell it explicitly how to map the values in your request to the Model you are expecting in the Register post method in your UserController.
This link shows an example of how to do it in ASP.NET Core. I couldn't find the ASP.NET MVC official documentation but it's not so different than this.
Hope it helps!

Changing HTML components to Standard components

I created a MVC-3 application (Once we create it we are given a login screen which is already developed). And it has used HTML components found in the toolbox to create text boxes, labels etc. But i want to use standard components found in the toolbox. How can i replace these HTML components with the standard components.
When the user clicks on the Login button, the username and password gets authenticated in the default sample application provided for us. I don't want to change its functionality but what i want is only to change the form components to the Standard components found in the toolbox.
How can i do this ?
<% using (Html.BeginForm()) { %>
<%: Html.ValidationSummary(true, "Login was unsuccessful. Please correct the errors and try again.") %>
<div>
<fieldset>
<legend>Account Information</legend>
<div class="editor-label">
<%: Html.LabelFor(m => m.UserName) %>
</div>
<div class="editor-field">
<%: Html.TextBoxFor(m => m.UserName) %>
<%: Html.ValidationMessageFor(m => m.UserName) %>
</div>
<div class="editor-label">
<%: Html.LabelFor(m => m.Password) %>
</div>
<div class="editor-field">
<%: Html.PasswordFor(m => m.Password) %>
<%: Html.ValidationMessageFor(m => m.Password) %>
</div>
<div class="editor-label">
<%: Html.CheckBoxFor(m => m.RememberMe) %>
<%: Html.LabelFor(m => m.RememberMe) %>
</div>
<p>
<input type="submit" value="Log On" />
</p>
</fieldset>
</div>
<% } %>
Are you talking about these:
<%: Html.TextBoxFor(m => m.UserName) %>
<%: Html.ValidationMessageFor(m => m.UserName) %>
These are called Html helpers. They are used in asp.net mvc to generate html that will play nice with the mvc model binder. If you want to replace them with plain html, you can always view source, see what the rendered html is and paste it in its place, though I don't personally see the point. Nothing good could come of this.
But this is what the two lines above render:
<input data-val="true" data-val-required="The User name field is required." id="UserName" name="UserName" type="text" value="" />
<span class="field-validation-valid" data-valmsg-for="UserName" data-valmsg-replace="true"></span>
Les see if I undesrtand, If when you say standard controls you mean ASP.NET Server Side Controls you can't I mean at least not using MVC and the reason is 'cause is like mixing apples and bananas you have to use either WebForms or MVC, if you choose MVC so you have to place the logic in a controller on an specific action that is going to be called once the form the button is inside of is clicked,but if you dont want to, so use a plain old aspx page add server side controls and put the logic on the click event of the button, but you can't mix MVC and WebForms that makes no sense (I'm saying this in a good way :) ) they're different paradigms.

Dynamically change style attributes in ASP.NET MVC

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>
<% } %>

Using xval to client side validate forms

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>()%>

Uploading an image in ASP.NET MVC using EDM

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/

Categories