manage date fields when are int in the db - forms

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.

Related

MVC 2 TextBoxFor doesn't work outside view

I wanted to remove repeated code from my 'edit' view forms by writing a method to generate the HTML for the field name, input box, and any validation messages. Here is an example of the default view code generated by the system:
<div class="editor-label">
<%: Html.LabelFor(model => model.dateAdded) %>
</div>
<div class="editor-field">
<%: Html.TextBoxFor(model => model.dateAdded, String.Format("{0:g}", Model.dateAdded)) %>
<%: Html.ValidationMessageFor(model => model.dateAdded) %>
</div>
And here is what I started to write:
MvcHtmlString DataField(HtmlHelper h, Object m)
{
string s=h.TextBoxFor(m => m.dateAdded);
}
Now I know that won't work properly, it's just a start, but I get the error "'System.Web.Mvc.HtmlHelper' does not contain a definition for 'TextBoxFor' and no extension method 'TextBoxFor' accepting a first argument of type 'System.Web.Mvc.HtmlHelper' could be found".
Are you trying to write a custom HTML helper that would generate this HTML? I would recommend you using a custom editor template because what you have is primary markup. So you could have the following partial (~/Views/Shared/EditorTemplates/SomeViewModel.ascx):
<%# Control
Language="C#"
Inherits="System.Web.Mvc.ViewUserControl<AppName.Models.SomeViewModel>" %>
<div class="editor-label">
<%: Html.LabelFor(model => model.dateAdded) %>
</div>
<div class="editor-field">
<%: Html.TextBoxFor(model => model.dateAdded, String.Format("{0:g}", Model.dateAdded)) %>
<%: Html.ValidationMessageFor(model => model.dateAdded) %>
</div>
and then whenever you have a strongly typed view to SomeViewModel simply:
<%= Html.EditorForModel() %>
or if you have a property of type SomeViewModel:
<%= Html.EditorFor(x => x.SomePropertyOfTypeSomeViewModel) %>
which would render the custom editor template.
As far as the helper is concerned the proper signature would be:
using System.Web.Mvc;
using System.Web.Mvc.Html;
public static class HtmlExtensions
{
public static MvcHtmlString DataField(this HtmlHelper<SomeViewModel> htmlHelper)
{
return htmlHelper.TextBoxFor(x => x.dateAdded);
}
}

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.

MVC2 model binding w/ many-to-many: at the cusp

I'm an inch away from getting my Create form working. My problem is that some data passed into the form in the view model isn't being sent back in the postback.
Models:
Game:
GameID - int (primary key, auto-incr)
GameTitle - nvarchar(100)
ReviewText - text
ReviewScore - smallint
Pros - text
Cons - text
LastModified - Datetime
GenreID - int (foreign key from Genres)
Platform:
PlatformID - int (primary key, auto-incr)
Name - nvarchar(50)
GamePlatform (not visible as an EF 4 entity):
GameID - int (foreign key from Games)
PlatformID - int (foreign key from Platforms)
The view models I'm using:
public class PlatformListing
{
public Platform Platform { get; set; }
public bool IsSelected { get; set; }
}
public class AdminGameReviewViewModel
{
public Game GameData { get; set; }
public List<Genre> AllGenres { get; set; }
public List<PlatformListing> AllPlatforms { get; set; }
}
And the form itself:
<%# Control Language="C#" Inherits="System.Web.Mvc.ViewUserControl<HandiGamer.WebUI.ViewModels.AdminGameReviewViewModel>" %>
<p>
<%: Html.Label("Game Title") %>
<%: Html.TextBoxFor(model => Model.GameData.GameTitle) %>
<%: Html.ValidationMessageFor(model => Model.GameData.GameTitle) %>
</p>
<p>
<%: Html.LabelFor(model => Model.GameData.GenreID) %>
<%: Html.DropDownListFor(m => Model.GameData.GenreID, new SelectList(Model.AllGenres, "GenreID", "Name", Model.GameData.GenreID)) %>
</p>
<p>
<%: Html.Label("Platforms") %><br />
<% for(var i = 0; i < Model.AllPlatforms.Count; ++i)
{ %>
<%: Model.AllPlatforms[i].Platform.Name %> <%: Html.CheckBoxFor(p => Model.AllPlatforms[i].IsSelected) %>
<% } %>
</p>
<p>
<%: Html.Label("Review") %>
<%: Html.TextAreaFor(model => Model.GameData.ReviewText) %>
</p>
<p>
<%: Html.Label("Review Score") %>
<%: Html.DropDownListFor(m => Model.GameData.ReviewScore, new SelectList(new int[] {1, 2, 3, 4, 5}))%>
</p>
<p>
<%: Html.LabelFor(model => model.GameData.Pros) %><br />
<%: Html.TextAreaFor(model => model.GameData.Pros) %>
</p>
<p>
<%: Html.LabelFor(model => model.GameData.Cons) %><br />
<%: Html.TextAreaFor(model => model.GameData.Cons) %>
</p>
And, finally, my Create method (barebones as I'm trying to get this to work):
[HttpPost]
public ActionResult CreateReview([Bind(Prefix = "GameData")]Game newGame, [Bind(Prefix = "AllPlatforms")]List<PlatformListing> PlatformList)
{
try
{
foreach(var plat in PlatformList)
{
if (plat.IsSelected == true)
{
newGame.Platforms.Add(plat.Platform);
}
}
newGame.LastModified = DateTime.Now;
_siteDB.Games.AddObject(newGame);
_siteDB.SaveChanges();
// add form data to entities, then save
return RedirectToAction("Index");
}
catch
{
return View();
}
}
The problem is, of course, with my checkboxes. The boolean isSelected is being set fine, but when the data is being posted, the corresponding Platform object is missing. I thought they would automatically be passed back. So, any suggestions on how to pass back the actual Platform part of a PlatformListing?
Regarding getting the checkbox values, how about using the strategy described here?
Regarding passing around entity objects as arguments, I'd say you're letting your data layer get mixed into your view layer, and you should use a dedicated ViewModel.

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.

Asp.Net MVC 2 Validation

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 :)