标签: model-binding

如何使用Jquery Ajax进行模型绑定

我想使用模型绑定来保持我的控制器看起来更干净,你可以看到使用模型绑定有多好:

public ActionResult Create(Person personToCreate)
{
    //Create person here
}
Run Code Online (Sandbox Code Playgroud)

VS

public ActionResult Create(string firstName, string lastName, string address, string phoneNum, string email, string postalCode, string city, string province, string country)
{
    //Create person here
}
Run Code Online (Sandbox Code Playgroud)

在进行模型绑定时,我们可以使用具有正确名称的表单 Html.TextBox("")

怎么样jquery?我怎样才能确保当我执行$.post(url, data, callback, dataType)$.ajax(options)调用Create(Person personToCreate)Person对象被正确填充时?

ajax asp.net-mvc jquery html-helper model-binding

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

如何从自定义模型绑定器中删除魔术字符串?

我现在写了几个自定义模型绑定器,并意识到我已陷入依赖魔术字符串的陷阱,例如:

    if (bindingContext.ValueProvider.ContainsPrefix("PaymentKey"))
    {
        paymentKey = bindingContext.ValueProvider.GetValue("PaymentKey").AttemptedValue;
    }
Run Code Online (Sandbox Code Playgroud)

我希望能够使用表达式强类型化前缀名称,但无法弄清楚如何,并将感谢一些帮助.

谢谢.

asp.net-mvc model-binding magic-string

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

ASP.NET MVC - 用于ICollection <T>的EditorTemplate问题映射到Enum

我有一个ASP.NET MVC 3(Razor)网站和一个名为Review的(简化)模型:

public class Review
{
   public int ReviewId { get; set; }
   public bool RecommendationOne
   {
       // hook property - gets/set values in the ICollection
   }
   public bool RecommendationTwo { // etc }
   public ICollection<Recommendation> Recommendations { get; set; }
}
Run Code Online (Sandbox Code Playgroud)

建议 如下:

public class Recommendation
{
   public byte RecommendationTypeId
}
Run Code Online (Sandbox Code Playgroud)

我还有一个名为RecommendationType枚举,用于将上述建议映射到.(基于RecommendationTypeId).

总而言之 - 单个Review许多Recommendations,并且每个Recommendations都映射到特定的枚举类型,我公开了钩子属性以简化模型绑定/代码.

所以,在视图上:

@Html.EditorFor(model => model.Recommendations, "Recommendations")
Run Code Online (Sandbox Code Playgroud)

很简单.

现在,对于编辑器模板,我想显示每个可能的RecommendationType(枚举)的复选框,如果模型具有该推荐(例如,在编辑视图上),我选中该复选框.

这就是我所拥有的:

@model IEnumerable<xxxx.DomainModel.Core.Posts.Recommendation>
@using xxxx.DomainModel.Core.Posts; …
Run Code Online (Sandbox Code Playgroud)

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

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

ASP.NET MVC - 下拉列表选择 - 部分视图和模型绑定

我是ASP.NET MVC的新手,我正在努力找到最好的方法来做到这一点.这可能很简单,但我只是想做正确的事情所以我想我会问.

让我们说我的模型是这样的:

任务 - ID,描述,AssignedStaffMember

StaffMember - Id,FirstName,LastName

在我看来,我想创建一个新任务.我创建了一个强类型的Razor视图,并且可以使用EditorFor为Description创建文本框但是AssignedStaffMember呢?

我想要一个当前所有员工的下拉列表,并且可以选择一个,然后将其提交给一个动作方法 NewTask(string description, StaffMember assignedStaffMember) ,或者我可以为staffId而不是StaffMember对象提供一个int,并在动作中查找它方法.

做这个的最好方式是什么?我需要去数据库以获取员工名单,所以这就是我的想法:

  1. 对员工下拉列表进行部分查看,将使用几次并用于@Html.Action("ListStaff", "Staff")调用它.然后动作方法有

    public ActionResult ListStaff()
    {
        IEnumerable<StaffMember> model = _serviceLayer.GetAllStaff();
        return PartialView(model);
    }
    
    Run Code Online (Sandbox Code Playgroud)

    但是我不确定它如何与模型绑定一起工作,我的理解是它必须有正确的名称才能提交表单,我需要将名称传递给局部视图以放置元素我猜?

  2. 不要让它调用控制器来获取工作人员,而是创建一个包含我的Task和IEnumerable possibleStaff集合的ViewModel.可能会将此信息发送到局部视图.

  3. 一个Html助手?

  4. 编辑器可以以某种方式使用?

哪一个(或者更多)最好?以及如何进行模型绑定?

asp.net-mvc partial-views model-binding razor

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

模型绑定到MVC 3中可能存在非顺序索引的列表?

我正在关注来自Phil Haack的http://haacked.com/archive/2008/10/23/model-binding-to-a-list.aspx上的信息

他谈到了非顺序指数:

<form method="post" action="/Home/Create">

<input type="hidden" name="products.Index" value="cold" />
<input type="text" name="products[cold].Name" value="Beer" />
<input type="text" name="products[cold].Price" value="7.32" />

<input type="hidden" name="products.Index" value="123" />
<input type="text" name="products[123].Name" value="Chips" />
<input type="text" name="products[123].Price" value="2.23" />

<input type="hidden" name="products.Index" value="caliente" />
<input type="text" name="products[caliente].Name" value="Salsa" />
<input type="text" name="products[caliente].Price" value="1.23" />

<input type="submit" />
</form>
Run Code Online (Sandbox Code Playgroud)

当您使用与TextBoxFor的模型绑定时,这在MVC3中是否可行?
这是使用sequentiel索引执行此操作的方法:

@Html.TextBoxFor(m => m[i].Value)
Run Code Online (Sandbox Code Playgroud)

如果不可能的话,如果我的指数不是连续的,我还能做些什么吗?

asp.net-mvc list model-binding indices

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

如何使用model属性作为接口在ASP.NET Web API中进行POST

假设我有一个模型:

public class Menu
{
    public string Name { get; set; }
    public IMenuCommand Next { get; set; }
}
Run Code Online (Sandbox Code Playgroud)

IMenuCommand 可以有不同的实现,如:

public class NextStepCommand : IMenuCommand
{
    public int Step { get; set; }
}

public class VoiceCommand : IMenuCommand
{
    public string Message { get; set; }
}
Run Code Online (Sandbox Code Playgroud)

我想将具有不同命令的菜单POST到ASP.NET Web API服务.我怎样才能做到这一点?

下面的请求将创建一个指定的对象Name,但Next命令将为null:

POST http://localhost/api/menus: {"name":"bob","next":{"step":1}}
Returns 201: {"Name":"bob","Next":null}
Run Code Online (Sandbox Code Playgroud)

默认Web API绑定器无法将我的请求参数映射到所需的C#类型 - 当然这是一个棘手的部分.我可以为基于接口的属性使用一些"known-type"属性,还是有其他方法来处理这种情况,可能是自定义模型绑定器?

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

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

通过反射将N包裹在Nullable <T>中

所以我有一个自定义通用模型绑定器,它同时处理T和Nullable <T>.
但我通过反射自动创建bindigs.我搜索整个应用程序域以查找标记有特定属性的枚举,并且我想要像这样绑定theese枚举:

  AppDomain
    .CurrentDomain
    .GetAssemblies()
    .SelectMany(asm => asm.GetTypes())
    .Where(
      t =>
      t.IsEnum &&
      t.IsDefined(commandAttributeType, true) &&
      !ModelBinders.Binders.ContainsKey(t))
    .ToList()
    .ForEach(t =>
    {
      ModelBinders.Binders.Add(t, new CommandModelBinder(t));
      //the nullable version should go here
    });
Run Code Online (Sandbox Code Playgroud)

但这是抓住了.我无法将Nullable <T>绑定到CommandModelBinder.
我正在考虑运行时代码的生成,但我从来没有这样做,也许市场上还有其他选择.任何想法实现这一目标?

谢谢,
Péter

.net c# asp.net-mvc model-binding system.reflection

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

asp.net 4.5 webforms模型绑定:支持客户端验证?

我是使用数据注释的asp.net 4.5 webforms模型绑定的忠实粉丝.

ASCX:

     <asp:FormView ItemType="Contact" runat="server" DefaultMode="Edit" 
     SelectMethod="GetContact" UpdateMethod="SaveContact">
        <EditItemTemplate>   

              <asp:ValidationSummary runat="server" ID="valSum" />

              Firstname: <asp:TextBox  runat="server"  ID="txtFirstname" Text='<%#: BindItem.Firstname %>' /> 


              Lastname: <asp:TextBox  runat="server"  ID="txtLastname" Text='<%#: BindItem.Lastname %>' />

              Email:  <asp:TextBox  runat="server"  ID="txtEmail" Text='<%#: BindItem.Email %>' />     

              <asp:Button ID="Button1"  runat="server" Text="Save" CommandName="Update" />
        </EditItemTemplate>   
    </asp:FormView>
Run Code Online (Sandbox Code Playgroud)

的.cs:

    public void SaveContact(Contact viewModel)
    {
        if (!Page.ModelState.IsValid)
        {
            return;
        }            
    }              

    public Contact GetContact() 
    {
         return new Contact();
    }
Run Code Online (Sandbox Code Playgroud)

模型:

    public class Contact
    {
        [Required]
        [StringLength(10, ErrorMessage="{1} tis te lang")]   
        public string …
Run Code Online (Sandbox Code Playgroud)

asp.net webforms model-binding client-side-validation data-annotations

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

在ASP.NET核心模型中使用Required和JsonRequired与JSON主体绑定

我正在使用ASP.NET Core 2.0,我有一个请求对象注释如下:

public class MyRequest
{
    [Required]
    public Guid Id { get; set; }

    [Required]
    public DateTime EndDateTimeUtc { get; set; }

    [Required]
    public DateTime StartDateTimeUtc { get; set; }
}
Run Code Online (Sandbox Code Playgroud)

在我的控制器中:

public async Task<IActionResult> HandleRequest([FromBody] MyRequest request)
{ /* ... */ }
Run Code Online (Sandbox Code Playgroud)

我注意到一个问题与模型绑定:当我发送包含该头的请求Content-Type设置为application/json和一个空的身体,我想到,request在我的控制器是nullModelState.IsValidfalse.

但是当我有这样的身体时:

{
  "hello": "a-string-value!"
}
Run Code Online (Sandbox Code Playgroud)

request不是null,它有一切的默认值,而且ModelState.IsValidtrue

这当然发生在我缺少所有Required属性的时候,并且唯一存在的名称与那里的属性不匹配(即使是这个单个参数的类型string,也与我的模型上的任何类型都不匹配).

所以在某种程度上,Required如果我的请求中没有任何内容,那些属性似乎正在起作用,但如果我的请求不为空,它们就不会做任何事情!

当我准备这个问题时,我注意到还有一个JsonRequired …

c# model-binding json.net asp.net-core-2.0

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

在Asp.Net Core上为MongoDB ObjectId创建ModelBinder

我正在尝试为我的模型中的ObjectId类型创建一个非常简单的模型绑定程序,但到目前为止似乎还无法使它工作。

这是模型联编程序:

public class ObjectIdModelBinder : IModelBinder
{
    public Task BindModelAsync(ModelBindingContext bindingContext)
    {
        var result = bindingContext.ValueProvider.GetValue(bindingContext.FieldName);
        return Task.FromResult(new ObjectId(result.FirstValue));
    }
}
Run Code Online (Sandbox Code Playgroud)

这是我编写的ModelBinderProvider:

public class ObjectIdModelBinderProvider : IModelBinderProvider
{
    public IModelBinder GetBinder(ModelBinderProviderContext context)
    {
        if (context == null) throw new ArgumentNullException(nameof(context));

        if (context.Metadata.ModelType == typeof(ObjectId))
        {
            return new BinderTypeModelBinder(typeof(ObjectIdModelBinder));
        }

        return null;
    }
}
Run Code Online (Sandbox Code Playgroud)

这是我尝试将body参数绑定到的类:

public class Player
{
    [BsonId]
    [ModelBinder(BinderType = typeof(ObjectIdModelBinder))]
    public ObjectId Id { get; set; }
    public Guid PlatformId { get; set; }
    public string Name …
Run Code Online (Sandbox Code Playgroud)

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

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