MVC3 converting date to string error - asp.net-mvc-3

When I try to convert date to string I get this error. So how can I fix this error ?
Templates can be used only with field access, property access, single-dimension array index, or single-parameter custom indexer expressions.
Here is my view:
<div class="editor-field">
#Html.TextBoxFor(x => x.date.ToString("MM-dd-yyyy"), new { #class = "date", #required = "required" })
#Html.ValidationMessageFor(model => model.date)
</div>
Then I have edited my class with the annotation then same result here is my class. My date parameter in my database table which name is "contents" which I used in my view "x=>x.date"
public class Common
{
[DisplayFormat(DataFormatString = "{0:MM/dd/yyyy}")]
public DateTime date { get; set; }
public class CommonModel
{
public content content{ get; set; }
}
}

Try This:
1) Put Data Annotation in your class like:
[DisplayFormat(ApplyFormatInEditMode = true, DataFormatString = "{0:MM/dd/yyyy}")]
public DateTime date { get; set; }
2) Replacing this line:
#Html.TextBoxFor(x => x.date.ToString("MM-dd-yyyy"), new { #class = "date", #required = "required" })
for this should work:
#Html.EditorFor(x => x.date, new { #class = "date", #required = "required" })

Related

Validation for textbox in MVC3

I need your help. I am working with MVC3-Razor application. I need to validate a textbox on View (.cshtml file) in such a way that, the starting 2 characters must be "PR" and 4th character must be "2". This is the requirement. How would i achieve this functionality? Any suggestions, it would be great help. Thanks for your precious time.
Model
public class RegisterModel
{
public int ID { get; set; }
[RegularExpression(#"^PR[a-zA-Z0-9]2([a-zA-Z0-9]*)$", ErrorMessage = "Please enter valid Name.")]
[Required(ErrorMessage = "Name is required.")]
public string Name { get; set; }
}
View
#using (Html.BeginForm("DYmanicControllerPage", "Test", FormMethod.Post, new { id = "FrmIndex" }))
{
<div>
#Html.LabelFor(m => m.Name)
#Html.TextBoxFor(m => m.Name)
#Html.ValidationMessageFor(m => m.Name)
</div>
}

Dropdownlist not selecting the preselected value-mvc3

I am having strange issue, MVC dropdown selected value is not preselected on page Load.
My Models are:
public class DocumentTypesViewModel
{
[Required(ErrorMessage = "DocumentType is required")]
public int OHDocumentTypeId { get; set; }
public string OHDocumentTypeDescription { get; set; }
}
public class ClientAdvancedSearchViewModel
{
[Display(Name = "Name")]
public string Name { get; set; }
[Display(Name = "DocumentType")]
public string DocumentTypeId { get; set; }
public IEnumerable<SelectListItem> DocumentTypes { get; set; }
}
In My Controllers I am populating the ClientAdvancedSearchViewModel like this
[HttpGet]
public ActionResult ClientAdvancedSearch()
{
ClientAdvancedSearchViewModel clientAdvancedSearchViewModel = iClientReferralRecordsRepository.GetDocumentMetadata();
//DocumentTypes Dropdown
var ddlDocumentTypes = iDocumentTypeRepository.GetDocumentTypes();
clientAdvancedSearchViewModel.DocumentTypes = new SelectList(ddlDocumentTypes, "OHDocumentTypeId", "OHDocumentTypeDescription",clientAdvancedSearchViewModel.DocumentTypeId);
return View(clientAdvancedSearchViewModel);
}
Finally in the View:
<td>
<div class="editor-label">
#Html.LabelFor(model => model.DocumentTypes)
</div>
<div class="editor-field">
#Html.DropDownListFor(x => x.DocumentTypeId, Model.DocumentTypes, "Please Select", new { #id = "ddlDocumentType" })
</div>
</td>
I believe the Name of the dropdown is same is x => x.DocumentTypeId, becuase of this I think, my value is not preselected.
This is the ViewSource for generated HTML for the Drop Down
<select id="ddlDocumentType" name="DocumentTypeId">
<option value="">Please Select</option>
<option value="20">records</option>
<option value="21"> record1</option>
..
How can I rename my dropdownlist name or How can I solve my problem?
Thank you
Updated: Added the missed line
ClientAdvancedSearchViewModel clientAdvancedSearchViewModel = iClientReferralRecordsRepository.GetDocumentMetadata();
Your code on your view is just right. You forgot to set the value for DocumentTypeId. This is your code as you posted:
[HttpGet]
public ActionResult ClientAdvancedSearch()
{
//DocumentTypes Dropdown
var ddlDocumentTypes = iDocumentTypeRepository.GetDocumentTypes();
clientAdvancedSearchViewModel.DocumentTypes = new SelectList(ddlDocumentTypes, "OHDocumentTypeId", "OHDocumentTypeDescription",clientAdvancedSearchViewModel.DocumentTypeId);
return View(clientAdvancedSearchViewModel);
}
And you missed this:
clientAdvancedSearchViewModel.DocumentTypeId = some_value;
Also, do you intend to have DocumentTypeId as an int instead of a string?
UPDATE:
You can also check that you set the id like this:
#Html.DropDownListFor(x => x.DocumentTypeId, new SelectList(Model.DocumentTypes, "Id", "Value", Model.DocumentTypeId), new { #id = "ddlDocumentType" })
Notice I used the overload with new SelectList. I don't remember all the overloads and I do it like that all the time, so you might check our the other overloads that suits your need.

Creating a list of radio buttons

I m working with asp.net mvc3 to create a list of radiobuttons. I need to get a list from the controller and display it in the view. For each corresponding list in the view I have YES/NO radio button and need to generate a string at the end saying for each item in the list if the radiobutton is yes then 1 else 0.
So for example if I have 10 items in the list then I need to display them in the view (default values of the items being false) and then generate a string on submit where each character in the string corresponds to the bool value of each item in the list.
Can anyone give me an idea how do I do this in mvc3 ?
Thanks for the help in advance.
UPDATE
Here is the code I am trying :
My class has two properties :
public List<Module> lstModules { get; set; } // gives the list of items
public List<bool> IsModuleActivelst { get; set; } //gives the bool values
Here in controller I need to create a list and the corresponding bool values for that. I am stuck here and not able to generate the code. Anyways I ll explain the pseudocode
public class MMController : Controller
{
[HttpGet]
public ActionResult Clients()
{
//I need to generate the list - using lstModules prop
// Assign the list with the predefined values and if not just give the default values- using IsModuleActivelst prop
}
}
Here I create the view :
#foreach (var i in Model.lstModules)
{
<div class="formlabel">
<div align="right" class="label">
#Html.LabelFor(model => model.lstModules):</div>
</div>
<div class="formelement">
<label for="radioYes" class="visible-enable" style="cursor:pointer;position:relative;">
#Html.RadioButtonFor(model => model.IsModuleActivelst, "True", new { #id = "radioYes", #style = "display:none;" })
<span>Yes</span></label>
<label for="radioNo" class="visible-disable" style="cursor:pointer;position:relative;">
#Html.RadioButtonFor(model => model.IsModuleActivelst, "False", new { #id = "radioNo", #style = "display:none;" })
<span>No</span></label>
</div>
}
I would recommend you to start by defining a view model that will represent the information that you need to be working with in the particular view. So far you have mentioned a list of modules where the user needs to set whether a module is active or not using a radio button (personally I would use a checkbox for True/False status but that's your own decision):
public class ModuleViewModel
{
public int Id { get; set; }
public string Name { get; set; }
public bool IsActive { get; set; }
}
public class MyViewModel
{
public IEnumerable<ModuleViewModel> Modules { get; set; }
}
Then you could define a controller that will populate the view model, render the form and have another action to handle the form submission:
public class HomeController : Controller
{
public ActionResult Index()
{
var model = new MyViewModel
{
// TODO: this information could come from a database or something
Modules = new[]
{
new ModuleViewModel { Id = 1, Name = "module 1", IsActive = true },
new ModuleViewModel { Id = 2, Name = "module 2", IsActive = true },
new ModuleViewModel { Id = 3, Name = "module 3", IsActive = false },
}
};
return View(model);
}
[HttpPost]
public ActionResult Index(MyViewModel model)
{
return Content(
string.Format(
"Thank you for selecting the following values: {0}",
string.Join(" ", model.Modules.Select(x => string.Format("model id: {0}, active: {1}", x.Id, x.IsActive)))
)
);
}
}
The last part is to define the view (~/Views/Home/Index.cshtml):
#model MyViewModel
#using (Html.BeginForm())
{
#Html.EditorFor(x => x.Modules)
<button type="submit">OK</button>
}
And finally the corresponding editor template that will automatically be rendered for each element of the Modules collection - notice that the name and location of the template is important - ~/Views/Shared/EditorTemplates/ModuleViewModel.cshtml:
#model ModuleViewModel
<div>
#Html.HiddenFor(x => x.Id)
#Html.HiddenFor(x => x.Name)
<h2>#Html.DisplayFor(x => x.Name)</h2>
#Html.Label("IsActiveTrue", "Yes")
#Html.RadioButtonFor(x => x.IsActive, "True", new { id = Html.ViewData.TemplateInfo.GetFullHtmlFieldId("IsActiveTrue") })
<br/>
#Html.Label("IsActiveFalse", "No")
#Html.RadioButtonFor(x => x.IsActive, "False", new { id = Html.ViewData.TemplateInfo.GetFullHtmlFieldId("IsActiveFalse") })
</div>

Telerik MVC Grid - Group by Date

I'm trying to use Telerik MVC Grid for an application which requires lots of filtering and grouping... On every model I have, it has a property DateTime for storing CreationDate. Sometimes when showing the grid to the user, time isn't important. Also, I had to use ViewModels to avoid circular references since I'm using LINQ.
The problem comes when resorting or grouping results by date. If I use the CreationDate field as a Datetime on my ViewModel and then give it Format on the View to show only date, it sorts fine, works fine, but when grouping it groups using the whole datetime value, so there wont never be anything groupedby. If I use the CreationDate as a string in the ViewModel, it shows fine the first time but will give error if resorting or grouping by date.
Here's the code I have for this case:
VIEWMODEL:
public class CenterViewModel
{
public int Id { get; set; }
public string Name{ get; set; }
public string CityName { get; set; }
public string Phone{ get; set; }
public string CreationDate { get; set; }
public bool Active { get; set; }
}
CONTROLLER:
[GridAction]
public ActionResult AjaxIndex()
{
var model = repository.GetAllRecords()
.Select(o => new CenterViewModel
{
Id = o.Id,
Name = o.Name,
CityName= o.City.Name,
Phone = o.Phone,
CreationDate = o.CreationDate .ToShortDateString(),
Active = o.Active
});
return View(new GridModel
{
Data = model
});
}
public ActionResult Index()
{
return View();
}
VIEW:
#model IEnumerable<CenterViewModel>
#(Html.Telerik().Grid<CenterViewModel>()
.Name("Grid")
.DataKeys(keys =>
{
keys.Add(p => p.Id);
})
.Columns(columns =>
{
columns.Bound(o => o.Name);
columns.Bound(o => o.CityName);
columns.Bound(o => o.Phone);
columns.Bound(o => o.CreationDate).Width(200);
columns.Bound(o => o.Active).Width(100)
.DataBinding(dataBinding => {
dataBinding.Ajax().Select("AjaxIndex", "Centers", null);
})
.Pageable()
.Sortable()
.Groupable()
.Filterable())
The above code would work only for the first load of data, when you resort or group by date it will throw the following exception: "Method 'System.String ToShortDateString()' has no supported translation to SQL." which makes sense, but, I think my intention is pretty clear now.
Does anyone know how to solve this issue? Thanks in advance,
One thing you could try is in your model to use a date that removes the time element. Then in the view, format the date.
VIEWMODEL:
public DateTime CreationDate { get; set; }
CONTROLLER:
var model = repository.GetAllRecords()
.Select(o => new CenterViewModel
{
Id = o.Id,
Name = o.Name,
CityName= o.City.Name,
Phone = o.Phone,
CreationDate = new DateTime(o.CreationDate.Year, o.CreationDate.Month, o.CreationDate.Day),
Active = o.Active
});
VIEW:
columns.Bound(o => o.CreationDate).Width(200).Format("{0:MM/dd/yyyy}");

Getting selected value from DropDownList in asp.net mvc 3

An article view model
public class ArticleViewModel : ViewModelBase
{
[Required(ErrorMessage = "Required")]
public string Title { get; set; }
[Required(ErrorMessage = "Choose the language")]
public BELocale Locale { get; set; }
}
public class BELocale : BEEntityBase
{
public string OriginalName { get; set; }
public string FriendlyName { get; set; }
public string TwoLetterISOName { get; set; }
}
A view "AddLocaleForArticle"
#model Models.ArticleViewModel
#using (Html.BeginForm("VefifyAddingLocaleForArticle", "Administration"))
{
#Html.TextBoxFor(m => m.Title, new { disabled = "disabled" })
#Html.DropDownListFor(m => m.Locale,
new SelectList(ViewBag.AvalaibleLocales, "ID", "OriginalName"), "Select a language"
)
#Html.ValidationMessageFor(m => m.Locale)
<input type="submit" value="Save" />
}
An action
public ActionResult VefifyAddingLocaleForPhoto(ArticleViewModel article)
{
//article.Locale == null for some reason.
//but article.Title isn't null, it contains the data
return RedirectToAction("AddingLocaleForPhotoSuccess", "adminka");
}
Why article.Locale is equal null and how to fix it?
When the form is submitted a dropdown list sends only the selected value to the controller. So you cannot expect it to populate an entire complex object such as BELocale using a dropdownlist. The best you could is to populate its ID property and fetch the remaining of the object from your data store using this id.
So you will have to modify your dropdownlist helper so that it is bound to the id property of the locale as first argument:
#Html.DropDownListFor(
m => m.Locale.ID,
new SelectList(ViewBag.AvalaibleLocales, "ID", "OriginalName"),
"Select a language"
)
Now inside the corresponding controller action you will get the id:
public ActionResult VefifyAddingLocaleForPhoto(ArticleViewModel article)
{
// article.Locale.ID will contain the selected locale id
// so you can use this information to fetch the corresponding BELocale object
...
}
You may fill dropdown like this in your view model
public List<KeyValuePair<int, String>> locale
{
get
{
return _localerepo.Findlocals().Select(x => new KeyValuePair<int, string>(x.ID, x.OriginalName)).ToList();
}
}
In your view use this
<%:Html.DropDownListFor(x => x.ID, new SelectList(Model.locale, "key", "value"), "--Select locale--")%>
<%= Html.ValidationMessageFor(model => model.ID)%>

Resources