Click here to Skip to main content
15,885,126 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
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:
C#
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:
C#
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 file:
C#
@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 controller action

======
C#
[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();
			
		}


.....

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???
Posted
Updated 17-Nov-15 4:35am
v5
Comments
Richard Deeming 11-Nov-15 16:22pm    
One of the form values you're expecting to be an integer is either missing, or is not an integer.

You'll need to debug your code to see what values are posted back to the server, and why they can't be converted to integers. I'd be suspicious of the SurveyItemCount field, which could be blank.
Krunal Rohit 12-Nov-15 0:25am    
Posting this much of code doesn't make sense. Rather debug your code and narrow down the problem.

-KR
F-ES Sitecore 17-Nov-15 10:59am    
use int.TryParse rather than int.Parse. Google for syntax examples.

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.
 
Share this answer
 
v3
Solution for the above problem is:
C#
[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();
			
		}


=========================Within the foreach loop i was using:
C#
foreach (var s in inputitems)

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 .

C#
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.
===================================
 
Share this answer
 
v2

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900