Tag: 模型绑定

更复杂(真实的)模型绑定?

滚动我,想象下面的例子: Public ViewResult GiveMeFruit(int personId, string personName, int personAge, int fruitId){ Person person = PersonService.GetPerson(personId); person.Name = personName; person.Age = age; person.Fruits.Add(FruitService.GetFruit(fruitId)); ViewData.Person = person; View(ViewData); } 这应该做得更好 Public ViewResult GiveMeFruit(Person person, IFruit fruit){ person.Fruits.Add(fruit); ViewData.Person = person; View(ViewData); } 我之前尝试过合适的模型绑定但是我无法正常工作。 所有示例都向您展示了如何使用一个非常简单的类型,从不使用多个复杂类型。 模型绑定器如何知道哪种类型的字段是什么? 如果有水果1和水果2怎么办? 活页夹如何知道我的IFruit界面使用哪种具体类型? 此外,我想知道如果我想给我的人提供一个IEnumerable水果它会如何工作。

MVC日期时间模型绑定

我在我的应用程序中使用2个kendo日期选择器: Start Date: @(Html.Kendo().DatePickerFor(m=>m.StartDate)) End Date: @(Html.Kendo().DatePickerFor(m=>m.EndDate)) Show 单击该按钮时,我会读取这些日期选择器客户端的值,并对API控制器进行POST。 我遇到的问题有时是DateTime参数被错误地解析,我使用的是en-GB文化(在我的web.config中指定),但是给定日期为2014年3月1日(3月1日),当值为由模型绑定器处理,它被解释为03/01/2014(1月3日)。 我的javascript如下: function getGraphData() { var startDatePicker = $(“#StartDate”).data(“kendoDatePicker”); var endDatePicker = $(“#EndDate”).data(“kendoDatePicker”); var param = { StartDate: kendo.toString(startDatePicker.value().toLocaleDateString(), “dd/MM/yyyy”), EndDate: kendo.toString(endDatePicker.value().toLocaleDateString(), “dd/MM/yyyy”) }; // Do post here } 我的模型如下: public class DateRangeParam { #region Constructors and Destructors /// /// Initializes a new instance of the […]

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

当我需要在WebApi / MVC应用程序中使用多个参数而不是单独的模型时,您能告诉我吗? 我有一个需要一些参数的动作。 [HttpPost] public InfoViewModel GetInfo(IEnumerable Ids, DocumentType type) { // to do smth } 我也可以将此操作转换为以下内容: [HttpPost] public InfoViewModel GetInfo(RequestViewModel model) { // to do smth } 我需要一个特殊模型用于第二种情况。 public class RequestViewModel { public IEnumerable Ids { get; set; } public DocumentType DocumentType { get; set; } } 我以JSON格式将数据发送到服务器。 你能告诉我这两种方法的优点和缺点吗? 谢谢。

用于generics类型的ASP.NET Web API模型绑定器

与对应的MVC问题一致 ,有没有办法在ASP.NET Web API中为generics类型创建模型绑定器? 如果是,那么如何在绑定器中处理类型检查和实例化? 假设模型绑定器用于URL参数,请考虑一下 [ModelBinder(typeof(MyTypeModelBinder))] public class MyType { //… } 和 public class MyTypeModelBinder : IModelBinder { public bool BindModel(HttpActionContext actionContext, ModelBindingContext bindingContext) { // check if type if valid? Something like this… if (!(bindingContext.ModelType.IsGenericType && bindingContext.ModelType.GetGenericTypeDefinition() == typeof(MyType))) { return false; } // create instance…using Activator? } }

ModelBinding:MVC4 / C中的POST数据(可能来自Ruby)#

我们正在与chargify http://www.chargify.com集成,我需要在我们的MVC4 / C#服务器中处理来自Chargify的webhooks。 Chargify以(ruby)方式发送POST数据 – 子对象在方括号中分隔,如下所示: POST /1ffaj2f1 HTTP/1.1 X-Chargify-Webhook-Signature: 526ccfd9677668674eaa6ba5d447e93a X-Chargify-Webhook-Id: 11238622 User-Agent: Ruby Host: requestb.in Content-Type: application/x-www-form-urlencoded Content-Length: 5159 Connection: close Accept-Encoding: gzip, deflate Accept: */*; q=0.5, application/xml id=11238622&event=payment_success&payload[subscription][activated_at]=2013-05-22%2001%3A25%3A20%20-0400&payload[subscription][balance_in_cents]=0&… 问题是在.NET端,默认模型绑定器不喜欢方括号[ ] ,而是期望子对象以点缀符号分隔,如abcd=value 我有什么选择让模型绑定器工作? 我能想到以下几点: 使用委托处理程序挂钩请求,读取req主体并将[]替换为点(。)。 然而,这至少感觉有点冒险 编写一个可以与[]一起使用的自定义模型绑定器 – 希望能够以某种方式委托给默认处理程序。 不知道怎么回事 – 但是很想听到一些想法。 只需在Action中使用formcollection参数即可。 处理表单集合键以基于键形成递归字典。 这也意味着我必须处理整个字符串(日期,ids等等) 什么是最好的方式,我该如何去做。

更改整数的默认NumberStyles?

我有一个具有整数属性的模型。 使用23443提交模型时,模型绑定器工作正常,并且该操作中的值可用。 但是如果使用千位分隔符(如23,443 )提交模型,则不会解析该值,并且属性为零。 但是我发现一个十进制类型的属性可能有千位分隔符,它会解析并正确填充。 我发现默认情况下Int32.Parse()不解析千位分隔符但Decimal.Parse()确实允许千位分隔符。 我不想写支票,如: public ActionResult Save(Car model, FormCollection form) { Int32 milage; if(model.MyProperty == 0 && Int32.TryParse(form[“MyProperty”], NumberStyles.AllowThousands, CultureInfo.InvariantCulture, out milage) { model.MyProperty = milage; } else ModelState.AddModelError(“Invalid”, “Property looks invalid”); […] } 每次我处理这些领域。 它看起来很丑陋,并将所有validation移出模型属性。 将属性的类型更改为十进制只是为了使模型绑定工作似乎不是一个明智的想法。 当我查看模型绑定器时,看起来它正在使用TypeConverter来完成从字符串到类型的转换。 看起来Int32Converter使用带有NumberStyles.Integer Int32.Parse() 。 有没有办法改变Int32Converter的行为,以允许默认情况下解析千位分隔符? 也许在整个应用程序中覆盖Int32.Parse()上的默认NumberStyles ? 或者添加我自己的模型绑定器,用NumberStyles.AllowThousands解析整数NumberStyles.AllowThousands唯一/正确的行动方案?

为什么我得到“修饰符’虚拟’对此项无效”错误?

我正在尝试使用下面的模型创建mvc应用程序:(代码很大。我认为这对你来说更容易理解) public class Job { public int JobId { get; set; } public string Name { get; set; } public List GetJobs() { List jobsList = new List(); jobsList.Add(new Job { JobId = 1, Name = “Operator” }); jobsList.Add(new Job { JobId = 2, Name = “Performer” }); jobsList.Add(new Job { JobId = 3, Name […]

发布到模型的MVC DropDownList值未绑定

DropDownLists可能是我最不喜欢使用MVC框架的部分。 我的表单中有几个下拉列表,我需要将选定的值传递给ActionResult,该ActionResult接受模型作为其参数。 标记看起来像这样: @Html.LabelFor(model => model.FileType) @Html.DropDownListFor(model => model.FileType.Variety, (SelectList)ViewBag.FileTypes) @Html.LabelFor(model => model.Status) @Html.DropDownListFor(model => model.Status.Status, (SelectList)ViewBag.Status) 我的控制器动作如下所示: [HttpPost] public ActionResult Create(int reviewid, ReviewedFile file) { if (ModelState.IsValid) { UpdateModel(file); } //repository.Add(file); return RedirectToAction(“Files”, “Reviews”, new { reviewid = reviewid, id = file.ReviewedFileId }); } 这应该都很好,除了下拉的值被发布为null。 当我进一步研究ModelState错误时,发现原因是: 从类型’System.String’到类型’PeerCodeReview.Models.OutcomeStatus’的参数转换失败,因为没有类型转换器可以在这些类型之间进行转换。 它应该不是这么难,但确实如此。 所以问题是; 为了正确绑定模型属性,我需要做什么? 顺便说一句,我知道我可以传入一个FormCollection对象,但这意味着更改我目前期望强类型模型参数的unit testing的重要部分。

派生属性上的自定义模型绑定不起作用

我有一个自定义的ModelBinder(MVC3),由于某种原因没有被解雇。 以下是相关的代码: 视图 @model WebApp.Models.InfoModel @using Html.BeginForm() { @Html.EditorFor(m => m.Truck) } EditorTemplate @model WebApp.Models.TruckModel @Html.EditorFor(m => m.CabSize) ModelBinder的 public class TruckModelBinder : IModelBinder { public object BindModel(ControllerContext controllerContext, ModelBindingContext bindingContext) { throw new NotImplementedException(); } } Global.asax中 protected void Application_Start() { … ModelBinders.Binders.Add(typeof(TruckModel), new TruckModelBinder()); … } InfoModel public class InfoModel { public VehicleModel […]

ASP.Net模型绑定 – WebForms

我被要求在ASP.Net WebForms项目上工作,我想像在ASP.Net MVC中那样使用ModelBinding。 我在解决这个问题上遇到了一些问题,如果可能的话,我希望得到一些帮助。 如果我想将模型绑定到Form上的对象,我需要在FormView,GridView等中执行此操作,但在此实例中,我想使用FormView。 下面的代码是我正在使用的简化版本,但是每个位相关。 <asp:TextBox runat="server" ID="txtName" Text="” /> <asp:TextBox runat="server" id="txtAge" Text=" ” /> 我有一个JQuery脚本试图将数据传回模型,但我一直收到内部500错误 $(document).ready(function() { $(“#MainContent_bttnInsert”) .click(function() { var params = { Name: “Dave”, Age: 55 } $.ajax({ type: “POST”, url: “default.aspx/TestBinding”, data: JSON.stringify(params), contentType: “application/json; charset=utf-8”, dataType: “json”, //success: function (data) { success: function () { alert(“it worked”); return […]