ASP MVC 3 - Localization with LocalizationDisplayNameAttribute - asp.net-mvc-3

Can somebody tell me what I'm doing wrong in this code:
public class LocalizationDisplayNameAttribute : DisplayNameAttribute
{
public LocalizationDisplayNameAttribute(string resourceKey)
{
ResourceKey = resourceKey;
}
public override string DisplayName
{
get
{
string displayName = App_GlobalResources.Global.ResourceManager.GetString(ResourceKey);
return string.IsNullOrEmpty(displayName)
? string.Format("[[{0}]]", ResourceKey)
: displayName;
}
}
private string ResourceKey { get; set; }
}
The culture is set to cs. I have two resources: Global.resx and Global.cs.resx, but when I run this application I always get string from Global.resx (it should be Global.cs.resx)

The following works fine for me:
public class LocalizationDisplayNameAttribute : DisplayNameAttribute
{
public LocalizationDisplayNameAttribute(string resourceKey)
{
ResourceKey = resourceKey;
}
public override string DisplayName
{
get
{
string displayName = Global.ResourceManager.GetString(ResourceKey);
return string.IsNullOrEmpty(displayName)
? string.Format("[[{0}]]", ResourceKey)
: displayName;
}
}
private string ResourceKey { get; set; }
}
View model:
public class MyViewModel
{
[LocalizationDisplayName("foo")]
public string Foo { get; set; }
}
Controller:
public class HomeController : Controller
{
public ActionResult Index()
{
return View(new MyViewModel());
}
}
View:
#model MyViewModel
#Html.LabelFor(x => x.Foo)
#Html.EditorFor(x => x.Foo)
Resources:
~/App_GlobalResources/Global.resx:
foo: foo
~/App_GlobalResources/Global.cs.resx:
foo: localized foo
~/web.config:
<system.web>
<globalization culture="cs" uiCulture="cs"/>
...
</system.web>
prints the correct localized value.

Related

insert data in two class(table) in Entity Framwork by rerlation many to many

i create two class in my model and create relation many to many by Entity
in sql my classes is created tables Properly
when i try to insert data in this table get show error "Object reference not set to an instance of an object." my cod is:
public class News
{
public int ID { get; set; }
public string Title { get; set; }
public string Content { get; set; }
public DateTime Date { get; set; }
public virtual Picture Picture { get; set; }
public virtual NewsType NewsType { get; set; }
public ICollection<Tag> Tag { get; set; }
public News(int id, string title, string content, DateTime date)
{
this.ID = id;
this.Title = title;
this.Content = content;
this.Date = date;
}
public News()
{
}
}
public class Tag
{
public int ID { get; set; }
public string Title { get; set; }
public ICollection<News> News { get; set; }
public Tag()
{
}
}
public class DatabaseContext : DbContext
{
public DatabaseContext()
: base("News")
{
}
static DatabaseContext()
{
Database.SetInitializer(new DropCreateDatabaseIfModelChanges<DatabaseContext>());
}
public DbSet<News> newsInfo { get; set; }
public DbSet<Picture> pictures { get; set; }
public DbSet<NewsType> Types { get; set; }
public DbSet<Tag> Tags { get; set; }
}
[HttpPost]
public ActionResult AddNews(NewsViewModel newsInfo)
{
using (Models.DatabaseContext dbContext = new DatabaseContext())
{
ViewData["Type"] = new SelectList(dbContext.Types.ToList(), "Id", "Title");
}
if (!ModelState.IsValid)
{
return View();
}
else
{
Models.DatabaseContext dbContext = new Models.DatabaseContext();
Models.News news = new Models.News();
news.Title = newsInfo.Title;
news.Content = newsInfo.Content;
news.Date = DateTime.Now;
string newsinput = newsInfo.Tag.cleanTag();
string[] tags = new string[] { };
if (newsinput != null)
{
tags = newsinput.Split(',');
}
foreach (string item in tags)
{
Tag findTag = dbContext.Tags.Where(x => x.Title == item).FirstOrDefault();
if (findTag != null)
{
news.Tag.Add(findTag)
////////////////////////show error in this line
}
}
news.NewsType = dbContext.Types.Find(Convert.ToInt32(Request.Form["rdb"]));
dbContext.newsInfo.Add(news);
dbContext.SaveChanges();
return View();
}

knockoutjs with mvc collection model binding

I'm using knockoutjs to render a collection of items. After allowing the user to do some inline editing I need to post the collection back to the server. However, the collection isn't being populated on the server because I'm not using the name="[0].Blah" naming convention. Does anyone know how to either render name attributes like this using knockoutjs OR how to create a model binder that will allow me to extract the values from the ValueProvider?
You can see a screenshot of the ValueProvider during debugging below.
http://i.imgur.com/zSU5Z.png
Here is my managed ViewModel:
public class FundLevelInvestmentUploadResult
{
public string FileName { get; set; }
public IList<FundLevelInvestmentViewModel> Items { get; set; }
public int NumberOfErrors { get; set; }
public bool ShowErrorsOnly { get; set; }
public FundLevelInvestmentUploadResult()
{
Items = new List<FundLevelInvestmentViewModel>();
}
}
Here is the managed class for "Items":
public class FundLevelInvestmentViewModel
{
private string _fund;
private string _fundType;
private string _date;
private string _netOfWaivedFees;
private string _waivedFees;
private string _bcip;
private string _fxRate;
public uint RowIndex { get; set; }
public int? DealCode { get; set; }
public bool DealCodeIsValid { get; set; }
public string Fund
{
get { return _fund; }
set { _fund = GetString(value); }
}
public bool FundIsValid { get; set; }
public string FundType
{
get { return _fundType; }
set { _fundType = GetString(value); }
}
public bool FundTypeIsValid { get; set; }
public string DateOfInvestment
{
get { return _date; }
set { _date = GetString(value); }
}
public bool DateOfInvestmentIsValid { get; set; }
public string NetOfWaivedFees
{
get { return _netOfWaivedFees; }
set { _netOfWaivedFees = GetString(value); }
}
public bool NetOfWaivedFeesIsValid { get; set; }
public string WaivedFee
{
get { return _waivedFees; }
set { _waivedFees = GetString(value); }
}
public bool WaivedFeeIsValid { get; set; }
public string BCIP
{
get { return _bcip; }
set { _bcip = GetString(value); }
}
public bool BCIPIsValid { get; set; }
public string ExchangeRateToUSD
{
get { return _fxRate; }
set { _fxRate = GetString(value); }
}
public bool ExchangeRateToUSDIsValid { get; set; }
public string FileName { get; set; }
private IList<string> _errors;
public IList<string> Errors
{
get { return _errors ?? (_errors = new List<string>());}
set { _errors = value; }
}
public bool Show { get; set; }
public FundLevelInvestmentViewModel()
{
Errors = new List<string>();
Show = true;
}
// knockoutjs is returning "null" instead of "" for a null object when calling ko.mapping.fromJS
private string GetString(string value)
{
if (value == "null")
return string.Empty;
return value;
}
}
Here is my knockout viewModel:
var viewModel = {
FileData: ko.observableArray([]),
validateFile: function (file, event) {
$.ajax({
type: 'post',
url: newUrl,
data: ko.mapping.toJS(file)
}).done(function (data) {
var newFile = ko.mapping.fromJS(data);
var index = file.Items.indexOf(file);
viewModel.FileData.replace(file, newFile);
});
}
};
If you are using version 2.1.0.0 or later of knockout you can render the name attribute as follows from an observable array.
<input data-bind='attr: { name: "Items["+$index()+"].DealCode"}' />

MVC 3, Radio buttons & Models

Given I have a Model object like ...
public class MyModel
{
public int SomeProperty { get; set; }
public int SomeOtherProperty { get; set; }
public IList<DeliveryDetail> DeliveryDetails { get; set; }
}
public DeliveryDetail
{
public string Description { get; set; }
public bool IsSelected { get; set; }
}
and I pass it through to a View like this ...
// Controller
public ActionResult Index()
{
MyModel myModel = Factory.CreateModelWithDeliveryDetails(x);
return View(myModel);
}
How would I render / bind a set of radio buttons (in the view)? Using the following code doesn't post the data back:
#foreach(var deliveryDetail in #Model.DeliveryDetails)
{
#deliveryDetail.Description
#Html.RadioButtonFor(x => deliveryDetail, false)
}
Selections in a radio button list are mutually exclusive. You can select only a single value. So binding a radio button list to a property of type IEnumerable doesn't make any sense. You probably need to adapt your view model to the requirements of the view (which in your case is displaying a radio button list where only a single selection can be made). Had you used a checkbox list, binding to an IEnumerable property would have made sense as you can check multiple checkboxes.
So let's adapt the view model to this situation:
Model:
public class MyModel
{
public string SelectedDeliveryDetailId { get; set; }
public IList<DeliveryDetail> DeliveryDetails { get; set; }
}
public class DeliveryDetail
{
public string Description { get; set; }
public int Id { get; set; }
}
Controller:
public class HomeController : Controller
{
public ActionResult Index()
{
var model = new MyModel
{
DeliveryDetails = new[]
{
new DeliveryDetail { Description = "detail 1", Id = 1 },
new DeliveryDetail { Description = "detail 2", Id = 2 },
new DeliveryDetail { Description = "detail 3", Id = 3 },
}
};
return View(model);
}
[HttpPost]
public ActionResult Index(MyModel model)
{
// Here you will get the id of the selected delivery detail
// in model.SelectedDeliveryDetailId
...
}
}
View:
#model MyModel
#using (Html.BeginForm())
{
foreach (var deliveryDetail in Model.DeliveryDetails)
{
#deliveryDetail.Description
#Html.RadioButtonFor(x => x.SelectedDeliveryDetailId, deliveryDetail.Id)
}
<button type="submit">OK</button>
}
You need another property for posted value::
public class MyModel
{
public int SomeProperty { get; set; }
public int SomeOtherProperty { get; set; }
public IList<DeliveryDetail> DeliveryDetails { get; set; }
public DeliveryDetail SelectedDetail { get; set; }
}
And in view:
#foreach(var deliveryDetail in #Model.DeliveryDetails)
{
#deliveryDetail.Description
#Html.RadioButtonFor(x => x.SelectedDetail, deliveryDetail)
}
In order this to work DeliveryDetail has to be Enum.

Creating Dropdown List in MVC3

I am trying to create a dropdown list to display all the value in a custom collection class
such as
public class MyCustomClassCollection
{
public List<MyCustomClass> {get;set;}
}
I want it to show the Description:string of each MyCustomClass
I tried
<%: Html.DropDownList "Description", MyCustomClass %>
Resharper suggests that I cast MyCustomClass to IEnemerable
but the server returns an unable to cast error.
Any Idea how I can create this DropDownList?
__Modification___
public class ViewModel
{
public Detail detail { get; set; }
}
public class Detail //Inherited from webservce
{
public CustomClassCollection {get;set;}
.... Other Properties, a.k.a Custom Classes
}
public class CustomClassCollection
{
public List<CustomClass> {get;set;}
}
public class CustomClass {
public int Id {get;set;}
public string Description{get;set;}
... other properties
}
public ActionResult Index(int? id, DateTime? date)
{
if (id.Equals(null))
id = ######### ;
if (date.Equals(null))
date = DateTime.Today;
var vm = new ViewModel
{
Detail = _repository.Detail((int)id,(DateTime)date)
};
return View(vm);
}
The second argument of the DropDownList helper must be an IEnumerable<SelectListItem> or a SelectList which implements this interface for that matter. So in your controller action organize in such a way that you convert your custom collection into an IEnumerable<SelectListItem>. As always you could start by writing a view model:
public class MyViewModel
{
public string SelectedDescription { get; set; }
public SelectList Descriptions { get; set; }
}
and then have your controller action query the custom list and populate the view model which will be passed to the view:
public ActionResult Index()
{
var descriptions = yourCustomCollection.MyCustomClass.Select(x => new
{
Value = x.Description,
Text = x.Description
});
var model = new MyViewModel
{
Descriptions = new SelectList(descriptions, "Value", "Text")
};
return View(model);
}
and finally in your strongly typed view:
<%= Html.DropDownListFor(x => x.SelectedDescription, Model.Decriptions) %>
UPDATE:
After posting your updated models (which by the way are still incomplete and impossible to compile as you haven't provided any property names), here's an example:
public class ViewModel
{
public int SelectedId { get; set; }
public Detail Detail { get; set; }
}
public class Detail
{
public CustomClassCollection MyCollection { get; set; }
}
public class CustomClassCollection
{
public List<CustomClass> CustomClass { get; set; }
}
public class CustomClass
{
public int Id { get; set; }
public string Description { get; set; }
}
public class HomeController : Controller
{
public ActionResult Index()
{
var vm = new ViewModel
{
Detail = new Detail
{
MyCollection = new CustomClassCollection
{
CustomClass = new List<CustomClass>
{
new CustomClass
{
Id = 1,
Description = "description 1",
},
new CustomClass
{
Id = 2,
Description = "description 2",
},
new CustomClass
{
Id = 3,
Description = "description 3",
},
}
}
}
};
return View(vm);
}
}
and in the view:
<%= Html.DropDownListFor(
x => x.SelectedId,
new SelectList(Model.Detail.MyCollection.CustomClass, "Id", "Description")
) %>
What you have to understand in order to define a dropdown list in ASP.NET MVC ius that you need 2 things:
A scalar property to bind the selected value to (SelectedId in my example)
A collection to bind the list to (Model.Detail.MyCollection.CustomClass in the example)

MvcSerializer().Deserialize(serialized,SerializationMode....)

In asp.net mvc 3.0, I want to Deserialize and object which is stored in an input hidden filed.
Here is the Serializable class :
[Serializable]
public class RegistrationData
{
public string Name { get; set; }
public string Email { get; set; }
}
and the this is how i generate hidden field :
<%: Html.Serialize("regData", Model,
Microsoft.Web.Mvc.SerializationMode.Signed)%>
but when I Deserialize it through following method, I get null values for my object :
var serialized = Request.Form["regData"];
if (serialized != null)
{
regData = (RegistrationData)newMvcSerializer().Deserialize(serialized,SerializationMode.Signed);
}
Can any one help me please?
Model
public class RegistrationData
{
public string Name { get; set; }
public string Email { get; set; }
}
View
#using (Html.BeginForm())
{
#Html.HiddenFor(m=>m.Name)
#Html.HiddenFor(m=>m.Email)
}
Controller
public ActionResult Foo(RegistrationData form)
{
//do
//form.Name ->> get name
}

Resources