本文整理匯總了C#中System.Web.Mvc.ModelBindingContext類的典型用法代碼示例。如果您正苦於以下問題:C# ModelBindingContext類的具體用法?C# ModelBindingContext怎麽用?C# ModelBindingContext使用的例子?那麽, 這裏精選的類代碼示例或許可以為您提供幫助。
ModelBindingContext類屬於System.Web.Mvc命名空間,在下文中一共展示了ModelBindingContext類的15個代碼示例,這些例子默認根據受歡迎程度排序。您可以為喜歡或者感覺有用的代碼點讚,您的評價將有助於係統推薦出更棒的C#代碼示例。
示例1: BindModel
public override object BindModel(ControllerContext controllerContext, ModelBindingContext bindingContext)
{
if (bindingContext.ModelType == typeof(AddSheduleViewModel))
{
HttpRequestBase request = controllerContext.HttpContext.Request;
var model = base.BindModel(controllerContext, bindingContext) as AddSheduleViewModel;
bindingContext.ModelState.Clear();
var shedule = request.Form["Shedule"];
Regex reg = new Regex(@"\d{1,2}:\d{1,2}");
MatchCollection matches = reg.Matches(shedule);
if (matches.Count != 0)
{
try
{
model.Shedule = matches.Cast<Match>().Select(x => TimeSpan.Parse(x.Value)).ToList();
}
catch(Exception ex)
{
NLog.LogManager.GetCurrentClassLogger().Error(ex);
bindingContext.ModelState.AddModelError("", "Неверно заполнено расписание");
}
}
return model;
}
else
{
return base.BindModel(controllerContext, bindingContext);
}
}
示例2: BindModel
public object BindModel(ControllerContext controllerContext,
ModelBindingContext bindingContext)
{
//get the car from the session
Cart cart = null;
if (controllerContext.HttpContext.Session != null)
{
cart = (Cart)controllerContext.HttpContext.Session[sessionKey];
}
//create the Cart if there wasn't one in the session data
if(cart == null)
{
cart = new Cart();
if (controllerContext.HttpContext.Session != null)
{
controllerContext.HttpContext.Session[sessionKey] = cart;
}
}
return cart;
}
示例3: ValidateModel
void ValidateModel(object model, ModelBindingContext bindingContext, List<int> validatedObjects = null)
{
validatedObjects = validatedObjects ?? new List<int>();
var typeDescriptor = GetTypeDescriptor(model, model.GetType());
// validate the model
foreach (ValidationAttribute attribute in typeDescriptor.GetAttributes().OfType<ValidationAttribute>()) {
if (!attribute.IsValid (bindingContext.Model)) {
bindingContext.ModelState.AddModelError(bindingContext.ModelName, attribute.FormatErrorMessage(bindingContext.ModelName));
}
validatedObjects.Add (model.GetHashCode());
}
// validate properties, recurse if necessary
foreach (PropertyDescriptor property in typeDescriptor.GetProperties()) {
var propInstance = property.GetValue (model);
foreach (ValidationAttribute attribute in property.Attributes.OfType<ValidationAttribute>()) {
if (!attribute.IsValid(propInstance)) {
bindingContext.ModelState.AddModelError(property.Name, attribute.FormatErrorMessage(property.Name));
if (propInstance != null) {
validatedObjects.Add(propInstance.GetHashCode());
}
}
else if (propInstance != null) {
ValidateModel(propInstance, bindingContext, validatedObjects);
}
}
}
}
示例4: BindModel
public object BindModel(ControllerContext controllerContext, ModelBindingContext bindingContext)
{
CheckPropertyFilter(bindingContext);
ExtensibleModelBindingContext newBindingContext = CreateNewBindingContext(bindingContext, bindingContext.ModelName);
IExtensibleModelBinder binder = Providers.GetBinder(controllerContext, newBindingContext);
if (binder == null && !String.IsNullOrEmpty(bindingContext.ModelName)
&& bindingContext.FallbackToEmptyPrefix && bindingContext.ModelMetadata.IsComplexType)
{
// fallback to empty prefix?
newBindingContext = CreateNewBindingContext(bindingContext, String.Empty /* modelName */);
binder = Providers.GetBinder(controllerContext, newBindingContext);
}
if (binder != null)
{
bool boundSuccessfully = binder.BindModel(controllerContext, newBindingContext);
if (boundSuccessfully)
{
// run validation and return the model
newBindingContext.ValidationNode.Validate(controllerContext, null /* parentNode */);
return newBindingContext.Model;
}
}
return null; // something went wrong
}
示例5: BindModel
/// <summary>
/// Binds the model to a value by using the specified controller context and binding context.
/// </summary>
/// <param name="controllerContext">The controller context.</param>
/// <param name="bindingContext">The binding context.</param>
/// <returns>
/// The bound value.
/// </returns>
public virtual object BindModel(ControllerContext controllerContext, ModelBindingContext bindingContext)
{
FacebookClient client = _config.ClientProvider.CreateClient();
dynamic signedRequest = FacebookRequestHelpers.GetSignedRequest(
controllerContext.HttpContext,
rawSignedRequest =>
{
return client.ParseSignedRequest(rawSignedRequest);
});
if (signedRequest != null)
{
string accessToken = signedRequest.oauth_token;
string userId = signedRequest.user_id;
client.AccessToken = accessToken;
return new FacebookContext
{
Client = client,
SignedRequest = signedRequest,
AccessToken = accessToken,
UserId = userId,
Configuration = _config
};
}
else
{
bindingContext.ModelState.AddModelError(bindingContext.ModelName, Resources.MissingSignedRequest);
}
return null;
}
示例6: BindModel
public object BindModel(ControllerContext controllerContext, ModelBindingContext bindingContext)
{
IPhotoService<User, PhotoAlbum, Photo, Friend> myPhotoService = new PhotoService<User, PhotoAlbum, Photo, Friend>(new FriendService<User, Friend>(new EntityHAVFriendRepository()), new EntityHAVPhotoAlbumRepository(), new EntityHAVPhotoRepository());
User myUserInfo = HAVUserInformationFactory.GetUserInformation().Details;
int myUserId = Int32.Parse(BinderHelper.GetA(bindingContext, "UserId"));
int myAlbumId = Int32.Parse(BinderHelper.GetA(bindingContext, "AlbumId"));
string myProfilePictureURL = BinderHelper.GetA(bindingContext, "ProfilePictureURL");
string selectedProfilePictureIds = BinderHelper.GetA(bindingContext, "SelectedProfilePictureId").Trim();
IEnumerable<Photo> myPhotos = myPhotoService.GetPhotos(SocialUserModel.Create(myUserInfo), myAlbumId, myUserId);
string[] splitIds = selectedProfilePictureIds.Split(',');
List<int> selectedProfilePictures = new List<int>();
foreach (string id in splitIds) {
if (id != string.Empty) {
selectedProfilePictures.Add(Int32.Parse(id));
}
}
return new PhotosModel() {
UserId = myUserId,
ProfilePictureURL = myProfilePictureURL,
Photos = myPhotos,
SelectedPhotos = selectedProfilePictures
};
}
示例7: BindModel
public override object BindModel(ControllerContext controllerContext, ModelBindingContext bindingContext)
{
ProjectNewViewModel model = (ProjectNewViewModel)bindingContext.Model ??
(ProjectNewViewModel)DependencyResolver.Current.GetService(typeof(ProjectNewViewModel));
bool hasPrefix = bindingContext.ValueProvider.ContainsPrefix(bindingContext.ModelName);
string searchPrefix = (hasPrefix) ? bindingContext.ModelName + ".":"";
//since viewmodel contains custom types like project make sure project is not null and to pass key arround for value providers
//use Project.Name even if your makrup dont have Project prefix
model.Project = new Project();
//populate the fields of the model
model.Project.ProjectId = 0;
model.Project.Name = GetValue(bindingContext, searchPrefix, "Project.Name");
model.Project.Url = GetValue(bindingContext, searchPrefix, "Project.Url");
model.Project.CreatedOn = DateTime.Now;
model.Project.UpdatedOn = DateTime.Now;
model.Project.isDisabled = GetCheckedValue(bindingContext, searchPrefix, "Project.isDisabled");
model.Project.isFeatured = GetCheckedValue(bindingContext, searchPrefix, "Project.isFeatured");
model.Project.GroupId = int.Parse(GetValue(bindingContext, searchPrefix, "Project.GroupId"));
model.Project.Tags = new List<Tag>();
foreach (var tagid in GetValue(bindingContext, searchPrefix, "Tags").Split(','))
{
var tag = new Tag { TagId = int.Parse(tagid)};
model.Project.Tags.Add(tag);
}
var total = model.Project.Tags.Count;
return model;
}
示例8: BindModel
public override object BindModel(ControllerContext controllerContext, ModelBindingContext bindingContext)
{
var displayFormat = bindingContext.ModelMetadata.DisplayFormatString;
var value = bindingContext.ValueProvider.GetValue(bindingContext.ModelName);
if (!string.IsNullOrEmpty(displayFormat) && value != null)
{
DateTime date;
displayFormat = displayFormat.Replace("{0:", string.Empty).Replace("}", string.Empty);
// use the format specified in the DisplayFormat attribute to parse the date
if (DateTime.TryParseExact(value.AttemptedValue, displayFormat, CultureInfo.InvariantCulture, DateTimeStyles.None, out date))
{
return date;
}
else
{
bindingContext.ModelState.AddModelError(
bindingContext.ModelName,
string.Format("{0} is an invalid date format", value.AttemptedValue)
);
}
}
return base.BindModel(controllerContext, bindingContext);
}
示例9: BindModel
public object BindModel(ControllerContext controllerContext, ModelBindingContext bindingContext)
{
var value = bindingContext.ValueProvider.GetValue(bindingContext.ModelName);
var date = value.ConvertTo(typeof(DateTime), CultureInfo.CurrentCulture);
return date;
}
示例10: SetProperty
protected override void SetProperty(ControllerContext controllerContext, ModelBindingContext bindingContext, System.ComponentModel.PropertyDescriptor propertyDescriptor, object value)
{
base.SetProperty(controllerContext, bindingContext, propertyDescriptor, value);
switch (propertyDescriptor.Name)
{
case "ClientName" :
if (string.IsNullOrEmpty((string)value))
{
bindingContext.ModelState.AddModelError("ClientName", "");
}
break;
case "Date":
if((bindingContext.ModelState.IsValidField("Date")) && (DateTime.Now>(DateTime)value))
{
bindingContext.ModelState.AddModelError("Date", "");
}
break;
case "TermsAccepted":
if (!(bool)value)
{
bindingContext.ModelState.AddModelError("TermsAccepted", "");
}
break;
}
}
示例11: BindModel
public object BindModel(ControllerContext controllerContext,
ModelBindingContext bindingContext)
{
ValueProviderResult valueResult = bindingContext.ValueProvider
.GetValue(bindingContext.ModelName);
ModelState modelState = new ModelState {Value = valueResult};
object actualValue = null;
try
{
if (!string.IsNullOrEmpty(valueResult.AttemptedValue))
{
actualValue = Convert.ToDecimal(valueResult.AttemptedValue,
CultureInfo.CurrentCulture);
}
}
catch (FormatException e)
{
modelState.Errors.Add(e);
}
bindingContext.ModelState.Add(bindingContext.ModelName, modelState);
return actualValue;
}
示例12: CreateModel
protected override object CreateModel(ModelBindingContext bindingContext, Type modelType)
{
if (IsBasicType(modelType))
{
return base.GetValue(controllerContext, modelName, modelType, modelState);
}
if (IsSimpleType(modelType))
{
ModelBinderResult
}
var instance = Activator.CreateInstance(modelType);
foreach (PropertyDescriptor descriptor in TypeDescriptor.GetProperties(instance))
{
if (IsBasicType(descriptor.PropertyType))
{
var obj = GetBinder(descriptor.PropertyType).GetValue(controllerContext, descriptor.Name, descriptor.PropertyType, modelState);
descriptor.SetValue(instance, obj);
}
else
{
descriptor.SetValue(instance, Activator.CreateInstance(descriptor.PropertyType));
BindComplexType(controllerContext, descriptor.PropertyType, descriptor.GetValue(instance), modelState);
}
}
return instance;
}
示例13: PerformBindModel
public static object PerformBindModel(ControllerContext controllerContext, ModelBindingContext bindingContext)
{
var idName = string.IsNullOrEmpty(bindingContext.ModelName) ? "id" : bindingContext.ModelName;
var valueProviderResult = bindingContext.GetValue(idName);
if (valueProviderResult == null)
{
return null;
}
var rawId = valueProviderResult.ConvertTo(typeof(string)) as string;
var parseResult = HiveId.TryParse(rawId);
if (parseResult.Success)
{
//add the bound value to model state if it's not already there, generally only simple props will be there
if (!bindingContext.ModelState.ContainsKey(idName))
{
bindingContext.ModelState.Add(idName, new ModelState());
bindingContext.ModelState.SetModelValue(idName, new ValueProviderResult(parseResult.Result, parseResult.Result.ToString(), null));
}
}
return parseResult.Result;
}
示例14: BindModel
public object BindModel(ControllerContext controllerContext, ModelBindingContext bindingContext)
{
if (controllerContext == null)
throw new ArgumentNullException("controllerContext", "controllerContext is null.");
if (bindingContext == null)
throw new ArgumentNullException("bindingContext", "bindingContext is null.");
var value = bindingContext.ValueProvider.GetValue(bindingContext.ModelName);
if (value == null) return null;
bindingContext.ModelState.SetModelValue(bindingContext.ModelName, value);
try
{
var date = value.ConvertTo(typeof(DateTime), CurrentRequestData.CultureInfo);
return date;
}
catch (Exception ex)
{
bindingContext.ModelState.AddModelError(bindingContext.ModelName, ex);
return null;
}
}
示例15: CreateModel
protected override object CreateModel(ControllerContext controllerContext, ModelBindingContext bindingContext, Type modelType)
{
string dataRuleTypeStr;
string dataruleTypeName = !string.IsNullOrWhiteSpace(bindingContext.ModelName) ? (bindingContext.ModelName + ".DataRuleType") : "DataRuleType";
dataRuleTypeStr = controllerContext.HttpContext.Request[dataruleTypeName];
if (string.IsNullOrEmpty(dataRuleTypeStr))
{
return null;
}
var dataRuleInt = Int32.Parse(dataRuleTypeStr);
DataRuleType dataRuleTypeEnum = (DataRuleType)dataRuleInt;
object model = null;
switch (dataRuleTypeEnum)
{
case DataRuleType.Folder:
model = new FolderDataRule();
break;
case DataRuleType.Schema:
model = new SchemaDataRule();
break;
case DataRuleType.Category:
model = new CategoryDataRule();
break;
}
bindingContext.ModelMetadata = ModelMetadataProviders.Current.GetMetadataForType(() => model, model.GetType());
return model;
}