MVC4自定义模型Binder错误 [英] MVC4 Custom Model Binder Error

查看:63
本文介绍了MVC4自定义模型Binder错误的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试将对象属性列表从cshtml传递到Httpost,将信息保存到Database sql 2008.

请参阅下面的代码。

我一直收到错误:

输入字符串的格式不正确。



描述:当前执行期间发生未处理的异常网络请求。请查看堆栈跟踪以获取有关错误及其源自代码的位置的更多信息。



异常详细信息:System.FormatException:输入字符串的格式不正确。







==================================== ================================================== = PPLEASE帮助!



已调试,发现SurveyID的值未从操作中发布到控制器



============================================== =======================

如果语法正确,请告诉我。

Custom模型绑定器:

Hi, I am trying to pass list of object attributes from a cshtml to Httpost that saves the info to the Database sql 2008.
See the code below.
I keep getting error :
Input string was not in a correct format.

Description: An unhandled exception occurred during the execution of the current web request. Please review the stack trace for more information about the error and where it originated in the code.

Exception Details: System.FormatException: Input string was not in a correct format.



=======================================================================================PPLEASE HELP!

Debugged and found that the value for SurveyID is not being posted to the controller from the action

=====================================================================
Please let me know if the syntax is right.
Custom model binder:

public class SurveysCustomBinder : IModelBinder
	{

		public object BindModel(ControllerContext controllerContext, ModelBindingContext bindingContext)
		{
			// Check whether the existing model objects, if not create a (if using a manual binding the bindingContext.Model won't be null)
			SurveyItems model = (SurveyItems)bindingContext.Model ?? (SurveyItems)DependencyResolver.Current.GetService(typeof(SurveyItems));
			// find out if the value provider has the required prefix
			bool hasPrefix = bindingContext.ValueProvider.ContainsPrefix(bindingContext.ModelName);   // The name bindingContext.ModelName to return the current model
			string searchPrefix = (hasPrefix) ? bindingContext.ModelName + "." : "";
			// To populate the model field object
			model.SurveyID = int.Parse(GetValue(bindingContext, searchPrefix, "SurveyID"));
			model.SurveyItemID = int.Parse(GetValue(bindingContext, searchPrefix, "SurveyItemID"));
			model.SurveyResultsID = int.Parse(GetValue(bindingContext, searchPrefix, "SurveyResultsID"));
			model.SurveyItemCount = int.Parse(GetValue(bindingContext, searchPrefix, "SurveyItemCount"));
			model.SurveyUserID = GetValue(bindingContext, searchPrefix, "SurveyUserID");
			//return model;




			//var SurveyID =Int32.Parse(request.Form.Get(SurveyID));
			//var SurveyItemID = Convert.ToInt32(request.Form.Get("SurveyItemID"));
			//var SurveyResultsID = Convert.ToInt32(request.Form.Get("SurveyResultsID"));
			//var SurveyItemCount = Convert.ToInt32(request.Form.Get("SurveyItemCount"));
			//string SurveyUserID = request.Form.Get("SurveyUserID");
			return new SurveyItems
			{
				SurveyID = model.SurveyID,
				SurveyItemID = model.SurveyItemID,
				SurveyResultsID = model.SurveyResultsID,
				SurveyItemCount = model.SurveyItemCount,
				SurveyUserID = model.SurveyUserID
			};
		}
		private string GetValue(ModelBindingContext context, string prefix, string key)
		{
			ValueProviderResult vpr = context.ValueProvider.GetValue(prefix + key);

			return vpr == null ? null : vpr.AttemptedValue;
		}

		private bool GetCheckedValue(ModelBindingContext context, string prefix, string key)
		{
			bool result = false;
			ValueProviderResult vpr = context.ValueProvider.GetValue(prefix + key);
			if (vpr != null)
			{
				result = (bool)vpr.ConvertTo(typeof(bool));
			}

			return result;
		}

	}



模型对象类:


Model Object class:

public class SurveyItems
    {

        public int SurveyID { get; set; }
        public int SurveyItemID { get; set; }
        public int SurveyResultsID { get; set; }

        [Required(ErrorMessage = "Digits only except a negative sign is allowed")]
        [Range(0, int.MaxValue)]
        public int? SurveyItemCount { get; set; }

        public string SurveyQuestion { get; set; }
        public string SurveyInstructions { get; set; }
        public string Sitems { get; set; }

        public string SurveyStatus { get; set; }

        public string SurveyUserID { get; set; }
    }





================

razor文件:



================
razor file:

@model IList<BusinessLayer.SurveyItems>
@using TDMIntranet.Models

@{
    ViewBag.Title="Please edit the item count for the Survey";
}
					 
@using (Html.BeginForm("EditSurveyBySurveyIDandCDS", "CorporateSurveyRequests", FormMethod.Post, new { enctype = "multipart/form-data" }))
{    
	@Html.ValidationSummary(true)    
	
	if (Model.Count > 0)
	{
		for (int i = 0; i < Model.Count; i++)
		{
					<div class="editor-label">							 						
					@Html.TextBoxFor(ModelItem => Model[i].SurveyItemCount, new{SurveyID = Model[i].SurveyID,SurveyItemID = Model[i].SurveyItemID})
					@Html.DisplayFor(ModelItem => Model[i].Sitems)		   
					</div>						
					@Html.DisplayFor(ModelItem => Model[i].SurveyID)<br />					
					@Html.DisplayFor(ModelItem => Model[i].SurveyItemID) <br />					
					@Html.DisplayFor(ModelItem => Model[i].SurveyResultsID) <br />
					@Html.DisplayFor(ModelItem => Model[i].SurveyUserID)
					@Html.HiddenFor(ModelItem => Model[i].SurveyResultsID)
					@Html.HiddenFor(ModelItem => Model[i].SurveyItemCount)
					@Html.HiddenFor(ModelItem => Model[i].SurveyUserID)
					@Html.HiddenFor(ModelItem => Model[i].SurveyID) 
					@Html.HiddenFor(ModelItem => Model[i].SurveyItemID)
	
		 
		
           
	}
	}
	
	<p>
            <input type="submit" value="Save" />
        </p> 



========

HTTPPost控制器动作



======


========
HTTPPost controller action

======

[HttpPost]
		public ActionResult EditSurveyBySurveyIDandCDS(IList<SurveyItems> inputitems)
			

		{
			try
			{
				if (ModelState.IsValid)
				{
					for (int i = 0; i < inputitems.Count; i++)
					{
						foreach (var s in inputitems)
						{
							if (s.SurveyItemCount >= 0)
							{
								SurveyItems sitems = new SurveyItems();
								sitems.SurveyID = s.SurveyID;
								sitems.SurveyItemID = s.SurveyItemID;
								sitems.SurveyResultsID = s.SurveyResultsID;
								sitems.SurveyItemCount = s.SurveyItemCount;
								string CDS = System.Web.HttpContext.Current.Session["CDSIDValue"].ToString().ToLower();
								sitems.SurveyUserID = CDS;
								
								SurveysBusinessLayer requestsBusinessLayer = new SurveysBusinessLayer();
								requestsBusinessLayer.AddSurveyResults(sitems);
								//TempData["notice"] = sitems.SurveyID + sitems.SurveyItemID + sitems.SurveyResultsID + CDS + sitems.SurveyItemCount;
								//ViewBag["items"] = sitems;
								//TempData["notice"] = sitems.SurveyID + sitems.SurveyItemID + sitems.SurveyResultsID + CDS + sitems.SurveyItemCount;
								return RedirectToAction("ThanksforTakingTheSurvey");
								//return View(sitems);
							}
						}
					}
				}

				else
				{

					TempData["notice"] = "Please enter a valid integer value for the Item count.";
					return RedirectToAction("EditSurveyResultsError");
				}

			}
			catch (Exception ex)
			{
				TempData["Notice"] = ex;
			}
			
			return View();
			
		}





.....



如何在每个调查的剃刀视图中传递SurveyID和SurveyItemID项目数:

@ Html.TextBoxFor(ModelItem => Model [i] .SurveyItemCount,new {SurveyID = Model [ i] .SurveyID,SurveyItemID = Model [i] .SurveyItemID})

?????这是正确的吗???



.....

How do i pass SurveyID and SurveyItemID in the razor view for each survey Item Count :
@Html.TextBoxFor(ModelItem => Model[i].SurveyItemCount, new{SurveyID = Model[i].SurveyID,SurveyItemID = Model[i].SurveyItemID})
????? Is this correct???

推荐答案

paramSurveyItemCount1.Value = Convert.ToInt32(0);



?大声笑....

只需在这里使用值为0的int而不是转换null ....

我也认为这是你的问题。



当你可以直接使用int 0时,不会将字符串0转换为int 0。



只是想知道你为什么要这么多转换为int?使用int而不是字符串?

Maby有一个原因,但我无法得到线索。
paramSurveyItemCount1.Value = Convert.ToInt32("0");

? lol....
Just use a int with value 0 here instead of converting a null....
I also think this is your problem.

Doesn't make any sence to convert a string 0 to a int 0 when you can use a int 0 direct.

Just wondering why are you converting so much to int? use a int than instead of strings?
Maby there is a reason for it but I can't get the clue.


上述问题的解决方案是:

Solution for the above problem is:
[HttpPost]
		public ActionResult EditSurveyBySurveyIDandCDS(IList<SurveyItems> inputitems)
			
 
		{
			try
			{
				if (ModelState.IsValid)
				{
					for (int i = 0; i < inputitems.Count; i++)
					{
						foreach (SurveyItems s in inputitems)
						{
							if (s.SurveyItemCount >= 0)
							{
								SurveyItems sitems = new SurveyItems();
								sitems.SurveyID = s.SurveyID;
								sitems.SurveyItemID = s.SurveyItemID;
								sitems.SurveyResultsID = s.SurveyResultsID;
								sitems.SurveyItemCount = s.SurveyItemCount;
								string CDS = System.Web.HttpContext.Current.Session["CDSIDValue"].ToString().ToLower();
								sitems.SurveyUserID = CDS;
								
								SurveysBusinessLayer requestsBusinessLayer = new SurveysBusinessLayer();
								requestsBusinessLayer.AddSurveyResults(sitems);
								//TempData["notice"] = sitems.SurveyID + sitems.SurveyItemID + sitems.SurveyResultsID + CDS + sitems.SurveyItemCount;
								//ViewBag["items"] = sitems;
								//TempData["notice"] = sitems.SurveyID + sitems.SurveyItemID + sitems.SurveyResultsID + CDS + sitems.SurveyItemCount;
								return RedirectToAction("ThanksforTakingTheSurvey");
								//return View(sitems);
							}
						}
					}
				}
 
				else
				{
 
					TempData["notice"] = "Please enter a valid integer value for the Item count.";
					return RedirectToAction("EditSurveyResultsError");
				}
 
			}
			catch (Exception ex)
			{
				TempData["Notice"] = ex;
			}
			
			return View();
			
		}





================== =======在我使用的foreach循环中:



=========================Within the foreach loop i was using:

foreach (var s in inputitems)



当我将其更改为低于代码工作而没有任何问题。

问题是我已将inputitems列表声明为var而不是将其定义为模型对象。




when i changed it to below the code worked without any issues.
Issue is that i have declared the list of inputitems as var instead of defining it as a model object .

foreach (SurveyItems s in inputitems)



================================ ==



感谢所有的建议!设置断点显然有帮助,我能够看到值,直到我找出问题。

===================================


==================================

Thanks for the suggestions all!Setting the break point did help obviously, i was able to see the values until the point where i figured out the issue.
===================================


这篇关于MVC4自定义模型Binder错误的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆