How to get ModelState Values in the ActionMethod of the Controller?
Here's my Index View Code -
My Code in Controller -
- using System;
- using System.Collections.Generic;
- using System.Linq;
- using System.Web;
- using System.Web.Mvc;
- using WebApplication1.Models;
-
- namespace WebApplication1.Controllers
- {
-
- public class HomeController : Controller
- {
- public ActionResult Index()
- {
- List<PokemonType> pokeTypes = new List<PokemonType>() {
- new PokemonType(){typeId = 1,pokeType = "Fire"},
- new PokemonType(){typeId = 2,pokeType = "Water"},
- new PokemonType(){typeId = 3,pokeType = "Thunder"},
- new PokemonType(){typeId = 4,pokeType = "Dark" }
- };
- Pokemon p = new Pokemon();
- SelectList sl = new SelectList(pokeTypes, dataValueField: "typeId", dataTextField: "pokeType", selectedValue: 4);
- TempData["typeId"] = sl;
- TempData.Keep();
-
- return View(p);
- }
-
- [HttpPost]
- public string Index(Pokemon p)
- {
- string isLegendary = "";
- if (p.isLegendary)
- {
- isLegendary = "Yes";
- }
- else
- {
- isLegendary = "No";
- }
-
-
- var type = ViewData.ModelState["typeId"].Value;
- var name = ViewData.ModelState["name"].Value;
- string s = $"Name: {name} <br>Height: {p.height} cm <br>Id: #{p.number} <br>Type: {type} <br>Is Legendary: {isLegendary}";
- return s;
- }
My Model Code -
- using System;
- using System.Collections.Generic;
- using System.Linq;
- using System.Web;
-
- namespace WebApplication1.Models
- {
- public class PokemonType
- {
- public int typeId { get; set; }
- public string pokeType { get; set; }
-
- public override string ToString()
- {
- return pokeType;
- }
- }
- public class Pokemon
- {
- public string name { get; set; }
- public float height { get; set; }
- public int number { get; set; }
-
- public int typeId { get; set; }
- public bool isLegendary { get; set; }
- }
With the Above code i get Output as -
Name:System.Web.Mvc.ValueProviderResult
Height: 99.7 cm
Id: #197
Type: System.Web.Mvc.ValueProviderResult
Is Legendary: Yes
Second method which i have tried is using Extension Method -
- public static string DisplayType(this SelectList selectList)
- {
- return selectList.DataTextField;
- }
and changing string in [HttpPost] Index method -
- string s = $"Name: {p.name} <br>Height: {p.height} cm <br>Id: #{p.number} <br>Type: {HelperClassExtension.DisplayType(TempData["typeId"] as SelectList)} <br>Is Legendary: {isLegendary}";
- return s;
With These Changes, My output is -
Name:Umbreon
Height: 99.7 cm
Id: #197
Type: pokeType
Is Legendary: No
So, I get pokeType instead of value Dark. (i've selected dark from the list.)
These are the things I have tried to retrieve the value of type(fire,water,thunder and dark). so, is there any way through which I can retrieve it?