标签: model-binding

将查询参数绑定到ASP.NET Core中的模型

我试图使用从查询参数到对象的模型绑定进行搜索.

我的搜索对象是

[DataContract]
public class Criteria 
{
  [DataMember(Name = "first_name")]
  public string FirstName { get; set; }
}
Run Code Online (Sandbox Code Playgroud)

我的控制器有以下操作

[Route("users")]
public class UserController : Controller 
{
  [HttpGet("search")]
  public IActionResult Search([FromQuery] Criteria criteria)
  {
    ...
  }
}
Run Code Online (Sandbox Code Playgroud)

当我按如下方式调用端点.../users/search?first_name=dave时,控制器操作的criteria属性为null.但是,我可以将端点称为蛇案例.../users/search?firstName=dave,而criteria属性包含属性值.在这种情况下,模型绑定已经起作用,但是当我使用snake_case时却没有.

如何在模型绑定中使用snake_case?

c# asp.net asp.net-mvc model-binding asp.net-core

18
推荐指数
3
解决办法
2万
查看次数

ASP.Net MVC 3 - JSON模型绑定到数组

我在ASP.Net MVC 3上,并且通过at中支持的功能列表,我应该能够获得默认的json模型绑定开箱即用.但是我还没有成功地将数组/集合从json绑定到action方法参数.虽然我确实得到了简单的json对象绑定正常工作.如果这里的专家可以告诉我我做错了什么,我将不胜感激.

这是代码:

服务器端代码优先:

//动作方法

 public JsonResult SaveDiscount(IList<Discount> discounts)
    {
       foreach(var discount in discounts)
       {
       ....
       }
    }
Run Code Online (Sandbox Code Playgroud)

//查看模型

public class Discount
{
    string Sku{get; set;}
    string DiscountValue{get; set;}
    string DiscountType{get; set;}

}
Run Code Online (Sandbox Code Playgroud)

//客户端(jquery/js):

    var discount = {};
    var jsondatacoll = [];
    $('#discountgrid tr').each(function () {

        sku = $(this).find("td").eq(1).html();
        discValue = $(this).find('.discval').val();
        discType = $(this).find('.disctype').val();

        discount = { Sku: sku, DiscountType: discType, DiscountValue: discValue};
        jsondatacoll.push(discount);
        }
    })
    if (jsondatacoll.length > 0) {
        var catalogDiscount = JSON.stringify(jsondatacoll);

        $.ajax(
        {
            url: …
Run Code Online (Sandbox Code Playgroud)

asp.net-mvc json model-binding asp.net-mvc-3

17
推荐指数
2
解决办法
1万
查看次数

将复选框绑定到MVC中的int数组/可枚举

@Html.CheckBox("orderNumbers", new { value = 1 })
@Html.CheckBox("orderNumbers", new { value = 2 })
@Html.CheckBox("orderNumbers", new { value = 3 })
@Html.CheckBox("orderNumbers", new { value = 4 })
@Html.CheckBox("orderNumbers", new { value = 5 })

[HttpPost]
public ActionResult MarkAsCompleted(IEnumerable<int> orderNumbers) { }

[HttpPost]
public ActionResult MarkAsCompleted(IEnumerable<string> orderNumbers) { }
Run Code Online (Sandbox Code Playgroud)

如果我在我的动作方法中使用第一个签名,我会得到一个空的IEnumerable.

如果我使用第二个签名,我确实收到了值,但我也收到了未选择值的假值(因为MVCs模式阴影所有复选框都带有隐藏字段).

我会收到类似的东西 orderNumbers = { "1", "2", "false", "4", "false" }

为什么我不能得到数字列表?

int checkbox ienumerable model-binding asp.net-mvc-3

17
推荐指数
3
解决办法
2万
查看次数

自定义模型Binder继承自DefaultModelBinder

我正在尝试为将继承的MVC 4构建自定义模型绑定器DefaultModelBinder.我想它在拦截任何接口的任何结合水平并尝试从称为一个隐藏字段加载所需的类型AssemblyQualifiedName.

这是我到目前为止(简化):

public class MyWebApplication : System.Web.HttpApplication
{
    protected void Application_Start()
    {
        ModelBinders.Binders.DefaultBinder = new InterfaceModelBinder();
    }
}

public class InterfaceModelBinder : DefaultModelBinder
{
    public override object BindModel(ControllerContext controllerContext, 
        ModelBindingContext bindingContext)
    {
        if (bindingContext.ModelType.IsInterface 
            && controllerContext.RequestContext.HttpContext.Request.Form.AllKeys.Contains("AssemblyQualifiedName"))
        {
            ModelBindingContext context = new ModelBindingContext(bindingContext);

            var item = Activator.CreateInstance(
                Type.GetType(controllerContext.RequestContext.HttpContext.Request.Form["AssemblyQualifiedName"]));

            Func<object> modelAccessor = () => item;
            context.ModelMetadata = new ModelMetadata(new DataAnnotationsModelMetadataProvider(),
                bindingContext.ModelMetadata.ContainerType, modelAccessor, item.GetType(), bindingContext.ModelName);

            return base.BindModel(controllerContext, context);
        }

        return base.BindModel(controllerContext, bindingContext);
    }
}
Run Code Online (Sandbox Code Playgroud)

示例Create.cshtml文件(简化):

@model …
Run Code Online (Sandbox Code Playgroud)

c# model-binding asp.net-mvc-4

17
推荐指数
1
解决办法
2万
查看次数

模型绑定是否通过asp.net mvc中的查询字符串工作

模型绑定是否也通过查询字符串工作?

如果我有一个获取请求,例如:

GET /Country/CheckName?Country.Name=abc&Country.Id=0 HTTP/1.1
Run Code Online (Sandbox Code Playgroud)

CountryController中的以下方法是否具有包含Id和Name属性的oCountry参数以及查询字符串中的值?

public ViewResult CheckCountryName(Country oCountry)
{
     //some code
     return View(oCountry);
}
Run Code Online (Sandbox Code Playgroud)

出于某种原因,我在OCountry对象中将Id称为0并将Name作为null.缺什么 ?

.net c# asp.net-mvc model-binding query-string

17
推荐指数
1
解决办法
1万
查看次数

为什么我的ApiController方法具有可为空参数的ModelState.IsValid失败?

我有一个接受几个参数的ApiController方法,如下所示:

    // POST api/files
    public HttpResponseMessage UploadFile
    (
        FileDto fileDto,
        int? existingFileId,
        bool linkFromExistingFile,
        Guid? previousTrackingId
    )
    {
        if (!ModelState.IsValid)
            return Request.CreateResponse(HttpStatusCode.BadRequest);

        ...
    }
Run Code Online (Sandbox Code Playgroud)

当我发布POST时,我将FileDto对象放在请求的正文中,并将其他参数放在查询字符串上.

我已经发现我不能简单地省略可以为空的参数 - 我需要将它们放在带有空值的查询字符串上.所以,当我不想为可空参数指定值时,我的查询看起来像这样:

http://myserver/api/files?existingFileId=&linkFromExistingFile=true&previousTrackingId=
Run Code Online (Sandbox Code Playgroud)

这与我的控制器方法匹配,并且当执行该方法时,可以为空的参数null(正如您所期望的那样).

但是,对ModelState.IsValid返回的调用false,当我检查它们时,它正在抱怨两个可以为空的参数.(模型的其他位没有错误).消息是:

值是必需的,但请求中不存在.

为什么它认为价值是必需的/不存在的?当然(a)中的值要求可为空的,和(b)的值是(排序的)本-中的一种方式的空杂交排序?

model-binding asp.net-web-api

16
推荐指数
2
解决办法
4304
查看次数

HttpPostedFileBase没有绑定到模型

这是我的ViewModel

public class FaultTypeViewModel
{
    [HiddenInput(DisplayValue = false)]
    public int TypeID { get; set; }

    [Required(ErrorMessageResourceType = typeof(AdministrationStrings), ErrorMessageResourceName = "FaultTypeNameRequired")]
    [Display(ResourceType = typeof(AdministrationStrings), Name = "FaultTypeName")]
    public string TypeName { get; set; }

    [Display(ResourceType = typeof(AdministrationStrings), Name = "FaultTypeDescription")]
    [DataType(DataType.MultilineText)]
    public string TypeDescription { get; set; }

    [Display(ResourceType = typeof(AdministrationStrings), Name = "FaultTypeImageFile")]
    public HttpPostedFileBase TypeImageFile { get; set; }

    [HiddenInput(DisplayValue = false)]
    public string TypeImageURL { get; set; }
}
Run Code Online (Sandbox Code Playgroud)

请注意,我有一个"TypeImageFile" HttpPostedFileBase我预计到模型传递到控制器BU我只是不断收到空模型绑定会纽带,财产形式.

这是视图中的相关代码:

@using (Html.BeginForm("AddFaultType","Administration", FormMethod.Post))
{

    <div …
Run Code Online (Sandbox Code Playgroud)

asp.net-mvc model-binding asp.net-mvc-3

16
推荐指数
1
解决办法
1万
查看次数

如何使用不同的名称绑定视图模型属性

有没有办法将视图模型属性作为html端具有不同名称和id值的元素进行反射.

这是我想要实现的主要问题.所以问题的基本介绍如下:

1-我有一个视图模型(作为示例),它为视图侧的过滤操作创建.

public class FilterViewModel
{
    public string FilterParameter { get; set; }
}
Run Code Online (Sandbox Code Playgroud)

2-我有一个控制器动作,它是为GETting表格值创建的(这里是过滤器)

public ActionResult Index(FilterViewModel filter)
{
return View();
}
Run Code Online (Sandbox Code Playgroud)

3-我认为用户可以过滤某些数据,并通过表单提交通过查询字符串发送参数.

@using (Html.BeginForm("Index", "Demo", FormMethod.Get))
{    
    @Html.LabelFor(model => model.FilterParameter)
    @Html.EditorFor(model => model.FilterParameter)
    <input type="submit" value="Do Filter" />
}
Run Code Online (Sandbox Code Playgroud)

4-我想在渲染视图输出中看到的是

<form action="/Demo" method="get">
    <label for="fp">FilterParameter</label>
    <input id="fp" name="fp" type="text" />
    <input type="submit" value="Do Filter" />
</form>
Run Code Online (Sandbox Code Playgroud)

5-作为解决方案,我想修改我的视图模型,如下所示:

public class FilterViewModel
{
    [BindParameter("fp")]
    [BindParameter("filter")] // this one extra alias
    [BindParameter("param")] //this one extra alias
    public string FilterParameter { …
Run Code Online (Sandbox Code Playgroud)

asp.net-mvc model-binding data-annotations razor asp.net-mvc-5

16
推荐指数
2
解决办法
1万
查看次数

模型绑定时在视图模型属性上查找自定义属性

我发现了很多关于为验证目的实现自定义模型绑定器的信息,但我还没有看到我正在尝试做什么.

我希望能够根据视图模型中属性的属性来操作模型绑定器要设置的值.例如:

public class FooViewModel : ViewModel
{
    [AddBar]
    public string Name { get; set; }
}
Run Code Online (Sandbox Code Playgroud)

AddBar就是

public class AddBarAttribute : System.Attribute
{
}
Run Code Online (Sandbox Code Playgroud)

我无法在自定义模型绑定器的BindModel方法中找到一种在查看模型属性上查找属性的简洁方法.这有效,但感觉应该有一个更简单的解决方案:

public class FooBarModelBinder : DefaultModelBinder
{
    public override object BindModel(ControllerContext controllerContext, ModelBindingContext bindingContext)
    {
        var value = base.BindModel(controllerContext, bindingContext);

        var hasBarAttribute = false;

        if(bindingContext.ModelMetadata.ContainerType != null)
        {
            var property = bindingContext.ModelMetadata.ContainerType.GetProperties()
                .Where(x => x.Name == bindingContext.ModelMetadata.PropertyName).FirstOrDefault();
            hasBarAttribute = property != null && property.GetCustomAttributes(true).Where(x => x.GetType() == typeof(AddBarAttribute)).Count() > 0;
        }

        if(value.GetType() == typeof(String) && …
Run Code Online (Sandbox Code Playgroud)

asp.net-mvc custom-attributes model-binding

15
推荐指数
1
解决办法
7287
查看次数

如何在复杂的嵌套对象上使用[Bind(Include ="")]属性?

我正在创建一个锁定清单,每个锁具有一个序列号(标题),一个关联的学校(SchoolCode)和5个相关的组合(具有Number,Combination和IsActive).我们正在使用Ncommon和linq并将它们设置为嵌套实体(Lock Has Many Combinations).

在表单上,​​我使用JQuery模板动态构建表单.其中SchoolCode和Title是基本表单元素,Combinations [index] .Number和Combinations [index] .Combination是子元素.

<form method="post" action="/Lockers.aspx/Locks/Add">     
<input type="hidden" name="SchoolCode" value="102">  
 Lock S/N: <input type="text" name="Title" value=""><br>     
 <div id="combinations">
<input type="hidden" name="Combinations[0].Number" value="1">  
<input type="text" name="Combinations[0].Combination" value=""> 
 <input type="radio" value="1" name="ActiveCombination"><br>
<input type="hidden" name="Combinations[1].Number" value="2">  
<input type="text" name="Combinations[1].Combination" value="">  
<input type="radio" value="2" name="ActiveCombination"><br>
<input type="hidden" name="Combinations[2].Number" value="3">  
<input type="text" name="Combinations[2].Combination" value=""> 
 <input type="radio" value="3" name="ActiveCombination"><br>
<input type="hidden" name="Combinations[3].Number" value="4"> 
 <input type="text" name="Combinations[3].Combination" value=""> 
 <input type="radio" value="4" name="ActiveCombination"><br>
<input type="hidden" name="Combinations[4].Number" value="5"> 
 <input type="text" name="Combinations[4].Combination" value=""> …
Run Code Online (Sandbox Code Playgroud)

asp.net asp.net-mvc model-binding asp.net-mvc-3

15
推荐指数
1
解决办法
3万
查看次数