Asp.Net MVC 2 Validation - asp.net-mvc-2

I am trying to use validations with ASP.NET MVC 2.
I am just validating a textbox value.
Below is my approach.
Create View -:
<%: Html.ValidationSummary(true)%>
<%: Html.TextBoxFor(model => model.Name, new { #class="input-standard"})%>
<%: Html.ValidationMessageFor(model => model.Name) %>
Model Property-:
[Required (ErrorMessage="Name Required")]
public virtual string Name { get; set; }
But if i keep the textbox empty and click on submit then still the ModelState.IsValidate prperty is returning true.
Please suggest what am i doing wrong.
Thanks.

Have you added <% Html.EnableClientValidation(); %> and a reference to the Microsoft MVC ajax validation javascript (MicrosoftMvcAjax.js and MicrosoftMvcValidation.js).
Edit: sorry just noticed this does not answer your question :)

Related

asp.net MVC the microsoft edit template not including displaying object data

I used the edit template view for visual studio and it creates a nice form for me. The problem is that none of the objects data is included in the form. for example see this code this section:
<div class="editor-label">
<%: Html.LabelFor(model => model.VideoDesc) %>
</div>
<div class="editor-field">
<%: Html.EditorFor(model => model.VideoDesc) %>
<%: Html.ValidationMessageFor(model => model.VideoDesc) %>
</div>
On the server side I have the following:
public ActionResult editvid(int id)
{
using (VideoDBEntities ent = new VideoDBEntities())
{
var vids = from myRow in ent.Videos
where (myRow.VideoId == id)
select myRow;
ViewData["model"] = vids.ToList()[0];
}
return View();
}
I am new to MVC and LINQ and trying to find my feet
thanks
Andy
If you are using a strongly typed view you can pass your video object as model.
It is done by sending it as a parameter in View() method.
View can be overloaded with model object, if you have no model you can leave it empty.
in this case you can simply define video variable and pass it to the View.
using (VideoDBEntities ent = new VideoDBEntities())
{
var video = ent.Videos.SingleOrDefault(x=> x.VideoId ==id);
return View(video );
}

Getting data from view to create controller in asp.net MVC

Getting data from view to create controller in asp.net MVC
I know this is very simple but I am just learning ASP.net MVC.
I have a Create controller and a create view (used the generator)
I can hard code data into the controller and that does get saved but I want to know how to get the data the user put on the form back into the controller.
My controller is like this.
public ActionResult Create(Seller newSeller)
{
if (ModelState.IsValid)
{
try
{
newSeller.SellerID = 34324442;
newSeller.State = "NA";
newSeller.UserType = "Seller";
newSeller.FirstName = "sdfasd";
newSeller.LastName = "dasdfadsf";
newSeller.Phone = "33333";
newSeller.Email = "dfasdfasdf";
// write to database
listingsDB.Sellers.AddObject(newSeller);
listingsDB.SaveChanges();
return RedirectToAction("Details", newSeller.SellerID);
}
catch(Exception ex)
{
}
}
return View(newSeller);
}
My view looks like this
<% using (Html.BeginForm()) {%>
<%: Html.ValidationSummary(true) %>
<fieldset>
<legend>Fields</legend>
<div class="editor-label">
<%: Html.LabelFor(model => model.SellerID) %>
</div>
<div class="editor-field">
<%: Html.TextBoxFor(model => model.SellerID) %>
<%: Html.ValidationMessageFor(model => model.SellerID) %>
</div>
... Lots of propterties and then
<p>
<input type="submit" value="Create" />
</p>
</fieldset>
<% } %>
<div>
<%: Html.ActionLink("Back to List", "Index") %>
</div>
I am using ASP.net MVC 2 if it matters.
You usually have two actions on the controller: one for rendering the form and one for processing the posted form values. Typically it looks like this:
public class SellerController: Controller
{
// used to render the form allowing to create a new seller
public ActionResult Create()
{
var seller = new Seller();
return View(seller);
}
// used to handle the submission of the form
// the seller object passed as argument will be
// automatically populated by the default model binder
// from the POSTed form request parameters
[HttpPost]
public ActionResult Create(Seller seller)
{
if (ModelState.IsValid)
{
listingsDB.Sellers.AddObject(seller);
listingsDB.SaveChanges();
return RedirectToAction("Details", new { id = seller.SellerID });
}
return View(seller);
}
}
then your view looks as you have shown, it contains a form and input fields allowing the user to fill each property of the model. When it submits the form, the second action will be invoked and the default model binder will automatically fill the action parameter with the values entered by the user in the form.

ASP.NET MVC Model With Dynamic Number of CheckBoxes

I have a database with a one-to-many relationship that I'm having a difficult time modeling in ASP.NET MVC. For the sake of simplicity, let's say table A represents office buildings, table B represents employees and table C creates the one-to-many relation between employees and buildings to indicate which employees have access to a particular building.
Employee
EmployeeId - int
FirstName - string
LastName - string
Office
OfficeId - int
Location - string
EmployeeOffice
EmployeeId - int
OfficeId - int
When new employees come on board, I'd like to assign them to any office buildings they would be able to access. To do this, the UI calls for check boxes for each individual office building. Checking the boxes grants the user access to the related office building.
[ ] - Office 1
[ ] - Office 2
[ ] - Office 3
[ ] - Office 4
My concern is, offices should be dynamic. In other words, an office (or offices) can come or go at any time.
The model is actually more complicated than what I have depicted. As such, I have a CreateEmployeeViewModel, which contains properties (with annotations) as follows:
public class CreateEmployeeViewModel
{
public string FirstName
{
get;
set;
}
public string LastName
{
get;
set;
}
public IDictionary Offices
{
get;
private set;
}
public CreateEmployeeViewModel(IDictionary offices)
{
Offices = offices;
}
}
My view resembles the following
<div>
<%: Html.LabelFor(model => model.FirstName) %>
</div>
<div>
<%: Html.TextBoxFor(model => model.FirstName) %>
<%: Html.ValidationMessageFor(model => model.FirstName) %>
</div>
<div>
<%: Html.LabelFor(model => model.LastName) %>
</div>
<div>
<%: Html.TextBoxFor(model => model.LastName) %>
<%: Html.ValidationMessageFor(model => model.LastName) %>
</div>
<!-- This is really ugly, so I welcome any suggested updates -->
<% foreach (KeyValuePair<int, string> office in Model.Offices) { %>
<label for="Office<%: office.Key %>"><%: office.Value %></label>
<input id="Office<%: office.Key %>" type="checkbox" value="<%: office.Key %>" />
<% } %>
When I click the submit button for the form, I expect to get back the strongly typed view model, in addition to the check boxes so that I know which offices to assign users to. I created my action method like the following:
public ActionResult Create(CreateUserViewModel user, FormCollection collection)
The reason for the additional FormCollection object is I was hoping I could get form values in addition to the ones found on the view model (e.g., the check boxes). Unfortunately, however, the collection contains only information for the properties found in my view model.
What is the right way to handle forms with this design in ASP.NET MVC 2.0?
You need to add the "name" attribute to your checkbox input elements - otherwise they will not show up in the FormCollection.

Passing Parameters from textboxes in a view to a controller in ASP.Net MVC2

I am trying out ASP.Net MVC2 by building a small sample website which, amongst other features provides the user with a 'Contact Us' page. The idea is to allow a user to enter their name, email address, message subject and message. To send the message the user clicks on an ActionLink. This is the view:
<% Html.BeginForm(); %>
<div>
<%: Html.Label("Name")%>
<br />
<%: Html.TextBox("txtName", "",new { style = "width:100%" })%>
<br />
<%: Html.Label("Email address")%>
<br />
<%: Html.TextBox("txtEmail", "", new { style = "width:100%" })%>
<br />
<%: Html.Label("Subject")%>
<br />
<%: Html.TextBox("txtSubject", "", new { style = "width:100%" })%>
<br />
<%: Html.Label("Message")%>
<br />
<%: Html.TextBox("txtMessage", "", new { style = "width:100%" })%>
</div>
<div style='text-align: right;'>
<%:
Html.ActionLink("Send", "SentEmail", new { name = Html.g, sender = "txtEmail", subject = "txtSubject", message="txtMessage" })
%>
</div>
<% Html.EndForm(); %>
The idea is once the ActionLink has been clicked a method in the controller is called into which the username, email address, subject and message will be passed. This is the method in the controller:
public ActionResult SentEmail(string name, string sender, string subject, string message)
{
//Send email here and then display message contents to user.
ViewData["Name"] = name;
ViewData["Message"] = message;
ViewData["ThankyouMessage"] = "Thank you for contacting us. We will be in touch as soon as possible.";
return View();
}
However... when I click the link the values which are passed into the method are null. I have tried creating a route to do this but it doesn't work either. Should I be using another method?
Thank you,
Morris
Actually to achieve what you want to is easier than in your sample. Never heard about Model classes, Model Binder and strong typed views? Here thery are
Model class
public class ContactUsModel
{
public string Name { get; set; }
public string Email { get; set; }
public string Subject { get; set; }
public string Message { get; set; }
}
Then in your controller you should have two action: the first that show the form with default values and the second that receive the form with the data placed by the user. These two actions maps exactly to the HttpGet and HttPost verbs.
[HttpGet]
public virtual ActionResult ContactUs() {
ContactUsModel model = new ContactUsModel();
return View(model);
}
[HttpPost]
public virtual ActionResult ContactUs( ContactUsModel model ) {
//e.g. Save the contact request to database
}
To use this your view shal be strong typed to the ContactUsModel class
<%# Control Language="C#" Inherits="System.Web.Mvc.ViewUserControl<ContactUsModel>" %>
<% using (Html.BeginForm()) { %>
<div>
<%: Html.LabelFor(model => model.Name) %><br />
<%: Html.TextBoxFor(model => model.Name, new { style = "width:100%" })%>
</div>
<div>
<%: Html.LabelFor(model => model.Email) %><br />
<%: Html.TextBoxFor(model => model.EMail, new { style = "width:100%" })%>
</div>
<div>
<%: Html.LabelFor(model => model.Subject) %><br />
<%: Html.TextBoxFor(model => model.Subject, new { style = "width:100%" })%>
</div>
<div>
<%: Html.LabelFor(model => model.Message) %><br />
<%: Html.TextAreaFor(model => model.Message, new { style = "width:100%" })%>
</div>
<div>
<input type="submit" value="Save" />
</div>
<% } %>
the magic of everything this is called ModelBinder. Please read more and more about MVC here.
The action link isn't going to trigger a http post nor will it pass in the values of your form fields, just a http get and not passing through any form data - ideally you'd use an input submit button to post the data. What is certain is that it is good practise that any request that causes creating/updating of data should be done via a http post.
Submit button would just be like.
<input type="submit" value="Send" />
You then have several ways of accessing the form data firstly you could use a FormCollection to access the data
[HttpPost]
public ActionResult SendEmail(FormCollection collection)
{
string email = collection["txtEmail"];
...
}
Secondly you could use the method parameters and rely on model binding, but you must make sure field names match the parameter name so
<%: Html.TextBox("txtEmail", "", new { style = "width:100%" })%>
...would require...
[HttpPost]
public ActionResult SendEmail(string txtEmail)
{
...
}
If this form isn't being posted to the same action thats return the view then you'd also need to change your begin form tag, ideal you should use 'using' with it as well. So you'd get:
<% using (Html.BeginForm("SendEmail", "<controller-name>"))
{ %>
.... form fields in here ...
<input type="submit" value="Send" />
<% } %>
If the button isn't suitable for your design you could use something like:
<input type="image" src="<%: Url.Content("~/Content/images/myimage.gif") %>" value="Send" />
This would have the same effect. To trigger a post from an a tag though you'd need to look at using javascript, I can't remember the exact syntax but off hand I think if you used jquery you'd be looking at something like: (form a single form page only)
Send
But then you create a dependency on javascript where as really you should try have your site degrade gracefully so it can be used by visitors with javascript disabled. There are perhaps more advanced way of achieving this whilst meeting design requirements but that can get heavily into client side code which is probably outside of what you want for your sample.

manage date fields when are int in the db

Hi in my db there is a field "date_start" type integer.
This is the part of form for this field
<div class="editor-label">
<%: Html.LabelFor(model => model.date_start) %>
</div>
<div class="editor-field">
<%: Html.TextBoxFor(model => model.date_start, new { #class = "calendar" })%>
<%: Html.ValidationMessageFor(model => model.date_start) %>
</div>
In the form i want that the field's format is date type.
and memorize it in int type after calling a my function for the convertion.
How can i manage it?
thanks
Okay. I'm assuming you have a Linq-generated class, which we'll call LGC, and in that class is a property of type int called date_start.
To start, wrap LGC in a another class:
public class LGCPageForm
{
public LGC BaseModel { get; set; }
public DateTime date_start_as_date { get; set; }
}
Set the LGCPageForm class to be your Page's Model class. That'll require some refactoring, but I think it's your best option. Now, in your form, you'll have something like:
<div class="editor-label">
<%: Html.LabelFor(model => model.date_start_as_date) %>
<%: Html.TextBoxFor(model => model.date_start_as_date, new { #class = "calendar" })%>
<%: Html.ValidationMessageFor(model => model.date_start_as_date) %>
</div>
Then, capturing your postback. You'll definitely want to implement validation via DataAnnotations, but this should get you started in the right direction:
[HttpPost]
public ActionResult SubmitWeirdDate(LGCPageForm form)
{
//I'm not sure if this is the conversion you want?
form.LGC.date_start = form.LGC.date_start_as_date.Ticks;
}
There's the UNIX timestamp for this, which is basically an integer (and can be stored as such). I have no clue how to implement this in ASP.NET though. Check if there's a class named TimeStamp which can take an integer upon construct (or later on), then look for a form element that takes a TimeStamp.
That said, I haven't got any experience at all in ASP.NET.