logo
Tags down

shadow

Binding parameter to complex type


By : karmabreath
Date : October 16 2020, 08:10 AM
I wish this helpful for you I have a navigation bar, with several links, like this: , I can achieve this with little change and with one trick
code :
<a href="MyController/Browse?id=1">MenuItem1</a>
public ActionResult Browse(ComplexVM complexVM)
{
return View(complexVM);
}
public class ComplexVM
{
    public int DepartmentId { get; set; }
    public string DepartmentName { get; set; }
    public ComplexVM()
    {
        this.DepartmentId = System.Convert.ToInt32(HttpContext.Current.Request("id").ToString);
        this.DepartmentName = "Your name from cache"; // Get name from your cache 
    }
}


Share : facebook icon twitter icon

MVC Model Binding a Complex Type to a Simple Type and Vice Versa


By : zdjingji
Date : March 29 2020, 07:55 AM
this will help I figured it out, it's possible!
To clarify, I needed to: transform a string or string array (of IDs) into a JSON structure for my hidden field value, then on post back, deserialize the JSON in the hidden field and transform the struct back into a simple string or string array (of IDs) for my domain object's property.
code :
public static MvcHtmlString AutoComplete<TModel>(
    this HtmlHelper<TModel> htmlHelper,
    Expression<Func<TModel, string>> idProp)
    where TModel : class
{
    TModel model = htmlHelper.ViewData.Model;
    string id = idProp.Compile().Invoke(model);

    string propertyName = idProp.GetPropertyName();

    Person[] people = new Person[] {
        new Person() { ID = id }
    };

    // Don't name the textbox the same name as the property,
    // otherwise the value will be whatever the textbox is,
    // if you care.
    MvcHtmlString textBox = htmlHelper.TextBox(propertyName + "_ac", string.Empty);

    // For me, the JSON is the value I want to postback
    MvcHtmlString hidden = htmlHelper.Hidden(propertyName, new JavaScriptSerializer().Serialize(people));

    return MvcHtmlString.Create(
        "<span class=\"AutoComplete\">" +
            textBox.ToHtmlString() +
            hidden.ToHtmlString() +
        "</span>");
}
public class AutoCompleteBinder<T> : DefaultModelBinder
    where T : class
{
    private IEnumerable<string> PropertyNames { get; set; }

    public AutoCompleteBinder(params Expression<Func<T, object>>[] idProperties)
    {
        this.PropertyNames = idProperties.Select(x => x.GetPropertyName());
    }

    protected override object GetPropertyValue(
        ControllerContext controllerContext, 
        ModelBindingContext bindingContext,
        PropertyDescriptor propertyDescriptor, 
        IModelBinder propertyBinder)
    {
        var submittedValue = bindingContext.ValueProvider.GetValue(bindingContext.ModelName);

        if (submittedValue != null && this.PropertyNames.Contains(propertyDescriptor.Name))
        {
            string json = submittedValue.AttemptedValue;

            Person[] people = new JavaScriptSerializer().Deserialize<Person[]>(json);

            if (people != null && people.Any())
            {
                string[] IDs = people.Where(x => !string.IsNullOrEmpty(x.ID)).Select(x => x.ID).ToArray();

                bool isArray = bindingContext.ModelType != typeof(string) && 
                    (bindingContext.ModelType == typeof(string[]) || 
                    bindingContext.ModelType.HasInterface<IEnumerable>());

                if (IDs.Count() == 1 && !isArray)
                    return IDs.First(); // return string
                else if (IDs.Count() > 0 && isArray)
                    return IDs.ToArray(); // return string[]
                else
                    return null;
            }
            else
            {
                return null;
            }
        }

        return base.GetPropertyValue(controllerContext, bindingContext, propertyDescriptor, propertyBinder);
    }
}
ModelBinders.Binders.Add(typeof(Employee), new AutoCompleteBinder<Employee>(e => e.ID, e => e.TeamIDs));

ASP.NET MVC parameter binding failing for complex type


By : Jon Hall
Date : March 29 2020, 07:55 AM
seems to work fine Your properties have private setters. You cannot possibly expect the model binder to be able to bind them. So add public setters:
code :
public sealed class ProfileKnockOutQuestionModel 
{
    /// <summary>
    /// Parameterless constructor is required for auto-passing GET/POST data to controller actions.
    /// </summary>
    public ProfileKnockOutQuestionModel() { }

    [Required]
    [DisplayName("Lead Type Id")]
    public Int32 AdminLeadType { get; set; }

    //[Required]
    //[DisplayName("Question Type")]
    [UIHint("GridForeignKey")]
    public Int16 QuestionTypeId { get; set; }

    [Required]
    [DisplayName("Question Text")]
    public String QuestionText { get; set; }

    [Required]
    [DisplayName("Pass Answer")]
    public String Answer1Text { get; set; }

    [Required]
    [DisplayName("Fail Answer")]
    public String Answer2Text { get; set; }

    [Required]
    [DisplayName("Price")]
    [DataType(DataType.Currency)]
    [Range(0, Int16.MaxValue)]
    public Decimal Price { get; set; }

    /// <summary>
    /// Public setters are required for passing GET/POST data to controller actions.
    /// </summary>
    public Int32 ProfileKnockOutQuestionId { get; set; }

    /// <summary>
    /// Public setters are required for passing GET/POST data to controller actions.
    /// </summary>
    public Int32 ProfileId { get; set; }

    /// <summary>
    /// Public setters are required for passing GET/POST data to controller actions.
    /// </summary>
    public Int32 ParentProfileId { get; set; }

    /// <summary>
    /// Public setters are required for passing GET/POST data to controller actions.
    /// </summary>
    public Int32 CustomerId { get; set; }

    /// <summary>
    /// Public setters are required for passing GET/POST data to controller actions.
    /// </summary>
    public Int32 AdminKnockOutQuestionId { get; set; }

    ...
}
$.ajax({
    url: "/mvc/Profiles/78219/SetKnockOutQuestions/1605111",
    data: JSON.stringify({ 
        questions: data,
        parentProfileId : 1605105 
    }),
    type: "POST",
    contentType: "application/json; charset=utf-8"
});

ASP.net WebApi Parameter Binding to complex type from URI


By : Arshad Khan
Date : March 29 2020, 07:55 AM
I wish this help you I want to create a REST webservice using ASP.net WebApi on .net 4.5 , How about making the enum nullable like this?
code :
public class Demographics
{
    public Gender? Gender { get; set; }
}

MVC model binding complex type that has a property of complex type collection with Angular JS


By : stillsilly
Date : March 29 2020, 07:55 AM
This might help you Change the models so that you get a direct relationship between the Content and the associated File (the Order property is unnecessary)
code :
public class CreateBlogVM
{
    [Required]
    [MaxLength(250)]
    public string Title { get; set; }
    public List<FileVM> Files { get; set; }
}
public class FileVM
{
    [Required]
    public string Content { get; set; }
    [Required]
    public HttpPostedFileBase Image { get; set; }
}
var fd = new FormData();
fd.append('Title', $scope.title);
for (var i=0; i<$scope.rows.length; i++)
{
    ....
    var content = $scope.rows[i].value;
    fd.append('Files[' + i + '].Content', content);
    ....
    var file = $scope.rows[i].file;
    fd.append('Files[' + i + '].Image', file);
}
....
public JsonResult Create(CreateBlogVM model)

Complex Parameter Binding (array of nested class) in Web API


By : a.np
Date : March 29 2020, 07:55 AM
wish help you to fix your issue I found the answer. In this case we can use indexing with [] to group attributes of an instance in a collection, so the first Min and Max values together maps to a single Range instance in the SelectedRanges list.
shadow
Privacy Policy - Terms - Contact Us © voile276.org