标签: model-binding

复选框已选中,但值未传递到 asp.net mvc 中的控制器

我正在 ASP.Net MVC 中开发应用程序并遇到奇怪的问题。在我看来,我将复选框显示为开/关开关,如下所示:

在此输入图像描述 在此输入图像描述

为此,我使用以下 jquery 代码

function checkSwitch()
{
  $('input.checkSwitch').each(function() {

    if($(this).attr('checked') == 'checked'){
        $(this).wrap('<div class="checkSwitch on" />');
    } else {
        $(this).wrap('<div class="checkSwitch off" />');
    }

    $(this).parent('div.checkSwitch').each(function() {
        $(this).append('<div class="checkSwitchInner"><div class="checkSwitchOn">On</div><div class="checkSwitchHandle"></div><div class="checkSwitchOff">Off</div></div>');
    });

  });
}

$(document).on('click', 'div.checkSwitch', function() {

var $this = $(this);

if($this.hasClass('off')){
    $this.addClass('on');
    $this.removeClass('off');
    $this.children('input.checkSwitch').attr('checked', 'checked');
} else if($this.hasClass('on')){
    $this.addClass('off');
    $this.removeClass('on');
    $this.children('input.checkSwitch').removeAttr('checked');
}

});
Run Code Online (Sandbox Code Playgroud)

在视图中显示复选框的 HTML 代码如下:

<script>
   checkSwitch();
</script>
@Html.CheckBoxFor(model => model.ENABLED, new { @class = "checkSwitch", @checked = "checked" })
Run Code Online (Sandbox Code Playgroud)

这里 ENABLED 是模型中的布尔字段,如下所示:

public …
Run Code Online (Sandbox Code Playgroud)

checkbox asp.net-mvc jquery model-binding

5
推荐指数
1
解决办法
6154
查看次数

通用接口类型上的 Web API 模型绑定

我有一个通用接口,表示实体的查询选项:

public interface IQueryOptions<TEntity> {
    IQueryable<TEntity> Apply(IQueryable<TEntity> query);
}
Run Code Online (Sandbox Code Playgroud)

现在我想使用查询字符串将查询选项传递到 WebApi 路由,并使用自定义模型绑定器构造 IQueryOptions。

IQueryOptions 可以是 SortingOptions<> 或 PagingOptions<>,具体取决于传递给 api 的查询字符串

API

public class DummyController : ApiController {

    // optional parameter - query options are not required
    public void Test([ModelBinder]IQueryOptions<MyEntity> queryOptions = null)
    {
        ...
    }

}
Run Code Online (Sandbox Code Playgroud)

模型绑定器

public class QueryOptionsModelBinder : IModelBinder {
    public bool BindModel(HttpActionContext actionContext...
}
Run Code Online (Sandbox Code Playgroud)

WebApi配置

var queryProvider = new SimpleModelBinderProvider(typeof(IQueryOptions<>), new QueryOptionsModelBinder());
config.Services.Insert(typeof(ModelBinderProvider), 0, queryProvider); 
Run Code Online (Sandbox Code Playgroud)

我目前无法让它工作。API 抛出以下错误:

Cannot create an instance of an interface. …
Run Code Online (Sandbox Code Playgroud)

c# asp.net-mvc model-binding asp.net-web-api asp.net-web-api2

5
推荐指数
0
解决办法
1057
查看次数

是否可以对查询参数使用 Web API 模型验证?

我目前正在尝试编写一个 Web API 应用程序,其中我想要验证的参数之一是查询参数(也就是说,我希望以表单形式传递它/route?offset=0&limit=100):

[HttpGet]
public async Task<HttpResponseMessage> GetItems(
    int offset = 0,
    int limit = 100)
{
    if (!ModelState.IsValid)
    {
        // Handle error
    }

    // Handle request
}
Run Code Online (Sandbox Code Playgroud)

特别是,我想确保“offset”大于0,因为负数会导致数据库抛出异常。

我直接采用了附加 a 的逻辑方法ValidationAttribute

[HttpGet]
public async Task<HttpResponseMessage> GetItems(
    [Range(0, int.MaxValue)] int offset = 0,
    int limit = 100)
{
    if (!ModelState.IsValid)
    {
        // Handle error
    }

    // Handle request
}
Run Code Online (Sandbox Code Playgroud)

这根本不会导致任何错误。

在对 ASP.NET 进行了大量痛苦的调试之后,在我看来,这可能根本不可能。特别是,因为offset参数是方法参数而不是字段,所以ModelMetadata是使用GetMetadataForType而不是 来创建的GetMetadataForProperty,这意味着PropertyName将会是null …

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

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

当我需要使用带有多个参数的 POST 方法而不是单独的模型时?

您能告诉我何时需要在 WebApi/MVC 应用程序中使用多个参数而不是单独的模型吗?

我有一个需要几个参数的操作。

[HttpPost]
public InfoViewModel GetInfo(IEnumerable<Guid> Ids, DocumentType type)
{
    // to do smth
}
Run Code Online (Sandbox Code Playgroud)

我也可以将此操作转换为以下内容:

[HttpPost]
public InfoViewModel GetInfo(RequestViewModel model)
{
   // to do smth
}
Run Code Online (Sandbox Code Playgroud)

我需要一个用于第二种情况的特殊模型。

public class RequestViewModel
{
    public IEnumerable<Guid> Ids { get; set; }
    public DocumentType DocumentType { get; set; }
}
Run Code Online (Sandbox Code Playgroud)

我以 JSON 格式将数据发送到服务器。您能告诉我这两种方法的优点和缺点吗?谢谢。

c# model-binding asp.net-web-api

5
推荐指数
1
解决办法
2999
查看次数

ASP.NET Core MVC - 模型绑定:使用属性 [FromBody] (BodyModelBinder) 绑定接口模型

我想从我的操作方法绑定一个接口模型,并请求内容类型为 application/json。我在操作方法中使用 [FromBody] 属性。

我尝试通过以下链接创建从 ComplexTypeModelBinder 派生的自定义 modelBinder:Asp.net Core 中的自定义模型绑定,3:模型绑定接口,但它不起作用,我的模型始终为空。后来我了解到,当您使用属性 [FromBody] 时,会调用 BodyModelBinder,并且在内部调用 JsonInputFormatter,并且它不使用自定义 modelBinder。

我正在寻找一种绑定我的界面模型的方法。我可以使用 MVC DI 将每个接口与其实现进行映射。我的操作方法定义为:

public async Task<IActionResult> Create(IOperator user)
    {
        if (user == null)
        {
            return this.BadRequest("The user can't not be null");
        }

        if (!this.ModelState.IsValid)
        {
            return this.BadRequest(this.ModelState);
        }

            IOperator op = await this.AuthenticationFrontService.CreateOperatorAsync(user.Login, user.Password, user.FirstName, user.LastName, user.ValidUntil, user.Role, user.Comment);
        return new CreatedAtActionResult("Get", "operators", new { id = ((Operator)op).Id }, op);
    }
Run Code Online (Sandbox Code Playgroud)

我通过在界面中使用 MetadataType 属性尝试了另一种解决方案,但它在命名空间 System.ComponentModel.DataAnnotations 中不存在,并且我读到 asp.net core mvc does not use …

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

5
推荐指数
1
解决办法
6125
查看次数

使用 asp.net core 和 Jquery 从 ajax 请求将对象绑定到 asp mvc 控制器

我正在努力将 json 数据从 ajax 请求发布到 asp mvc 控制器方法,但由于某些未知原因,asp mvc 模型绑定器未绑定它。

我尝试遵循此处发布的多个答案,包括以下内容

将 json 对象发布到 ASP MVC 无法正常工作

但我的 jQuery ajax 方法总是将 null 值发送到 asp mvc 控制器。

基本上,我试图通过 ajax 请求加载部分视图。

阿贾克斯请求

var myData =
 {
        "Id": 7,
        "Name": "Name 1"
 };

  var obj = { 'test': myData };
  var val = JSON.stringify(obj);
  console.log(val);

  $.ajax({
    type: 'POST',
    dataType: 'html',
    url: '/Home/Partial',
    contentType: 'application/json',
    data: val,
    success: function (xhr, status, response) {
             console.log(response);
             $('#1').html(response.responseText);
         },
    error: function (err) {
        alert("error - " + …
Run Code Online (Sandbox Code Playgroud)

asp.net-mvc jquery model-binding asp.net-core

5
推荐指数
1
解决办法
3877
查看次数

模型绑定布尔单选按钮如何在 .NET Core 中工作?

我在使用标签助手将布尔视图模型属性绑定到 .NET Core 中的单选按钮时遇到问题。

<fieldset class="form-group">
    <div class="row">
        <label asp-for="AffectsUsers" class="col-sm-2 col-form-label text-right">Affects Users?</label>
        <div class="col-sm-10">
            <div class="mt-2">
                <div class="form-check form-check-inline">
                    <input class="form-check-input" asp-for="AffectsUsers" type="radio" value="true" />
                    <label class="form-check-label" asp-for="AffectsUsers">Yes</label>
                </div>
                <div class="form-check form-check-inline">
                    <input class="form-check-input" asp-for="AffectsUsers" type="radio" value="false" />
                    <label class="form-check-label" asp-for="AffectsUsers">No</label>
                </div>
            </div>
            <span asp-validation-for="AffectsUsers" class="text-danger"></span>
        </div>
    </div>
</fieldset>
Run Code Online (Sandbox Code Playgroud)

我有一个基于 ID 绑定到单选按钮的 jQuery 更改事件。

$('#AffectsUsers').change(function() {
   if (this.value === 'true') { ... } else { ... }
});
Run Code Online (Sandbox Code Playgroud)

仅针对第一个单选按钮调用该事件。我认为这是因为我正在使用单选按钮标签助手,它使用相同的 ID 创建多个输入。

如何将视图模型中的布尔值绑定到单选按钮,以便更改事件能够根据控件的值做出适当的响应?

model-binding asp.net-core-mvc asp.net-core-tag-helpers

5
推荐指数
1
解决办法
8442
查看次数

ASP.NET CORE 2.1 FromRoute 和 FromBody 模型绑定

我阅读了 Microsoft 关于构建 Web API的文档,但除了开发自定义模型绑定器之外,我没有看到有关如何合并路由和正文参数的示例。我相信我错过了一些东西,因为开发自定义模型绑定器对于这个常见任务来说似乎有点过分了。如何告诉我的应用程序从路由参数和主体有效负载创建模型?

Request:
PUT /business/f8e5cf33-40b1-4b8e-8280-b1b60a459154
{"name": "MyBusiness", "street": "123 Main Street"}

Response:
400
{"Id": ["'Id' must not be empty."]}

// BusinessController
[Route("business/{id}")]
[ApiController]
public class BusinessController : Controller {
    [HttpPut]
    [ProducesResponseType(400)]
    public ActionResult PutAsync(BusinessModel business) {
      ...
    }
}

// BusinessModel
class BusinessModel {
    // The `[FromRoute]` annotation has no affect
    public Guid Id { get; set; }
    public string Name { get; set; }
    public string Street { get; set; }
}
Run Code Online (Sandbox Code Playgroud)

asp.net model-binding asp.net-web-api

5
推荐指数
1
解决办法
3892
查看次数

如何在 asp.net core web api 的控制器中使用模型绑定排除属性

您好,当模型到达控制器(Web API)中的操作时,我试图从模型中排除一个属性,

我尝试过[Bind(Exclude ="something")],但似乎它不属于 .net core api

model-binding asp.net-web-api asp.net-core

5
推荐指数
3
解决办法
7662
查看次数

.net core razor 页面中的多个视图组件未正确绑定

我正在使用 razor 页面创建一个 .net core 5 web 应用程序,并且正在努力将我创建的视图组件绑定到我的页面——如果我在页面上有多个相同的视图组件。

以下工作完美:

我的页面.cshtml:

@page
@model MyPageModel
<form id="f1" method="post" data-ajax="true" data-ajax-method="post">
    <vc:my-example composite="Model.MyViewComposite1" />
</form>
Run Code Online (Sandbox Code Playgroud)

我的页面.cshtml.cs

[BindProperties]
public class MyPageModel : PageModel
{
    public MyViewComposite MyViewComposite1 { get; set; }

    public void OnGet()
    {
        MyViewComposite1 = new MyViewComposite() { Action = 1 };
    }

    public async Task<IActionResult> OnPostAsync()
    {
        // checking on the values of MyViewComposite1 here, all looks good...
        // ...
        return null;
    }
}
Run Code Online (Sandbox Code Playgroud)

MyExampleViewComponent.cs:

public class MyExampleViewComponent : ViewComponent
{ …
Run Code Online (Sandbox Code Playgroud)

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

5
推荐指数
1
解决办法
421
查看次数