Help, what did I do wrong? Full version of the error:
System.InvalidOperationException: The model element passed to the dictionary has the type "System.Int32", but this dictionary requires the model element of the type "Labs5.Models.Calc".
Listing Calc.cs:
using System; using System.Collections.Generic; using System.Linq; using System.Web; using System.ComponentModel.DataAnnotations; namespace Labs5.Models { public class Calc { [Required(ErrorMessage ="Число не введено")] public int a { get; set; } public string[] CalcRes; } } Listing SquareController.cs:
using Labs5.Models; using System; using System.Collections.Generic; using System.Linq; using System.Web; using System.Web.Mvc; namespace Labs5.Controllers { public class SquareController : Controller { [HttpGet] // GET: Square public ActionResult Calculate() { return View(); } [HttpPost] public ActionResult CalculateResult(Calc calcx) { calcx.CalcRes = new string[calcx.a]; int a = calcx.a; int sq = a * a; //calcx.CalcRes[sq] = String.Format("{0} = {1}", a, sq); return View("CalculateResult", sq); } } } Listing of Calculate.cshtml
@using System.Web.Optimization; @using Labs5.Models @model Calc @{ Layout = null; } <!DOCTYPE html> <html> <head> <meta name="viewport" content="width=device-width" /> <title>Calc</title> @Scripts.Render("~/scripts/jquery-1.8.0.js") @Scripts.Render("~/scripts/jquery.unobtrusive-ajax.js") </head> <body> <div> @using (Ajax.BeginForm("CalculateResult", new AjaxOptions { UpdateTargetId = "results" })) { <p> @Html.Label("Введите число") @Html.EditorFor(c=>ca) </p> <p> <input type="submit" value="Вычислить" /> </p> } <div id="results"></div> </div> </body> </html> Listing CalculateResult.cshtml
@using Labs5.Models @model Calc <h2>CalculateResult</h2> <body> Ответ: Корень @Model.a равен @Model.CalcRes </body> <a href="/Square/Calculate">Вычислить еще</a>
@Html.EditorFor(c=>ca)on the form, and in the controller you want to getCalculateResult(Calc calcx). How do you think your editor for a simple asp.net int field will collect yourCalctype? He (asp.net) does not know, so he swears, they say, "you sent a number editor to me, how can I give you some other type of this number"? :) - tym32167 Nov.