locked
How to get ModelState Values in the ActionMethod of the Controller ? RRS feed

  • Question

  • User-250884976 posted

    Here's my Index View Code - 

    @using (Html.BeginForm("Index", "Home"))
    {
    @Html.LabelFor(p => p.name, "Name: ")
    @Html.TextBoxFor(p => p.name)
    <br />
    @Html.LabelFor(p => p.height, "Height: ")
    @Html.TextBoxFor(p => p.height)
    <br />
    @Html.LabelFor(p => p.number, "Id: ")
    @Html.TextBoxFor(p => p.number)
    <br />
    @Html.LabelFor(p => p.typeId, "Type : ")
    @Html.DropDownList("typeId", TempData["typeId"] as SelectList)
    <br />
    @Html.LabelFor(p => p.isLegendary, "Is Legendary")
    @Html.CheckBoxFor(p => p.isLegendary)
    <br />
    <input type="submit" name="btnSumit" value="Submit" />
    }

    Please, tell me how can I access ModelState Values from the Index Action Method with [HttpPost<g class="gr_ gr_7 gr-alert gr_gramm gr_inline_cards gr_run_anim Style multiReplace" id="7" data-gr-id="7">] ?</g> 

    Wednesday, October 16, 2019 11:09 AM

Answers

  • User-17257777 posted

    Hi slalithp,

    Set “pokeTypes” as a global field, and then you can get “pokeType” via “typeId”. Test with the following codes.

    public class HomeController : Controller
        {
            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" }
            };
    
            public ActionResult Index()
            {
                Pokemon p = new Pokemon();
                SelectList sl = new SelectList(pokeTypes, dataValueField: "typeId", dataTextField: "pokeType", selectedValue: 4);
                TempData["typeId"] = sl;
                TempData.Keep();
                return View();
            }
    
            [HttpPost]
            public string Index(Pokemon p)
            {
                string isLegendary = "";
                if (p.isLegendary)
                {
                    isLegendary = "Yes";
                }
                else
                {
                    isLegendary = "No";
                }
                var type = pokeTypes.Find(t => t.typeId == p.typeId).ToString();
                string s = $"Name: {p.name}  <br>Height: {p.height} cm <br>Id: #{p.number}  <br>Type: {type}  <br>Is Legendary: {isLegendary}";
                return s;
            }
        }
    

    Result:

    Best Regards,

    Jiadong Meng

    • Marked as answer by Anonymous Thursday, October 7, 2021 12:00 AM
    Thursday, October 17, 2019 3:06 AM

All replies

  • User-1038772411 posted

    Hello,

    I had write below sample code for your solution.

    Here's my Index View Code

    @using (Html.BeginForm("Edit", "Home", FormMethod.Post,new { Model}))
    {
        @Html.LabelFor(p => p.name, "Name: ")
        @Html.TextBoxFor(p => p.name)
        <br />
        @Html.LabelFor(p => p.height, "Height: ")
        @Html.TextBoxFor(p => p.height)
        
        <br />
        @Html.LabelFor(p => p.number, "Id: ")
        @Html.TextBoxFor(p => p.number)
        <br />    
        @Html.LabelFor(p => p.isLegendary, "Is Legendary")
        @Html.CheckBoxFor(p => p.isLegendary)
        <br />
        <input type="submit" name="btnSumit" value="Submit" />
        @Html.AntiForgeryToken()
    }

    Here is my model class

     public class SampleModel
        {
            public string name { get; set; }
            public string height { get; set; }
            public string number { get; set; }      
            public bool isLegendary { get; set; }
        }

    Here is my controller where I created postback method

    [HttpPost, ValidateAntiForgeryToken]
    public ActionResult Edit(SampleModel sm)
    {
          if(ModelState.IsValid)
          {
               return RedirectToAction("Index", "Home");
          }
          return RedirectToAction("Index", "Home");
    }

    If you want any other details please share your code so that we can Identify your error.

    Thanks.

    Wednesday, October 16, 2019 1:37 PM
  • User-250884976 posted

    Hello, 

    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();
                //TempData.Keep();
                return View(p);
            }
    
            [HttpPost]
            public string Index(Pokemon p)
            {
                string isLegendary = "";
                if (p.isLegendary)
                {
                    isLegendary = "Yes";
                }
                else
                {
                    isLegendary = "No";
                }
    
                //ModelState.Clear();
                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;
            }

    and My Model is - 

    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 PokemonType type { get; set; }
            public int typeId { get; set; }
            public bool isLegendary { get; set; }
        }

    So, i am printing out string to the browser on submit request, with the current code i have got an out put like this - 

    Name:System.Web.Mvc.ValueProviderResult
    Height: 99.7 cm
    Id: #197
    Type: System.Web.Mvc.ValueProviderResult
    Is Legendary: Yes

    and <g class="gr_ gr_504 gr-alert gr_tiny gr_spell gr_inline_cards gr_run_anim ContextualSpelling multiReplace" id="504" data-gr-id="504">i</g> also tried it differently using <g class="gr_ gr_503 gr-alert gr_gramm gr_inline_cards gr_run_anim Grammar only-ins replaceWithoutSep" id="503" data-gr-id="503">extension</g> 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;

    Now <g class="gr_ gr_505 gr-alert gr_tiny gr_spell gr_inline_cards gr_run_anim ContextualSpelling multiReplace" id="505" data-gr-id="505">i</g> get <g class="gr_ gr_502 gr-alert gr_gramm gr_inline_cards gr_run_anim Grammar only-ins doubleReplace replaceWithoutSep" id="502" data-gr-id="502">output</g> as - 

    Name<g class="gr_ gr_511 gr-alert gr_gramm gr_inline_cards gr_run_anim Style replaceWithoutSep" id="511" data-gr-id="511">:Umbreon</g>
    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. so, is there any way through which I can review it? 

    Wednesday, October 16, 2019 3:31 PM
  • User-17257777 posted

    Hi slalithp,

    Set “pokeTypes” as a global field, and then you can get “pokeType” via “typeId”. Test with the following codes.

    public class HomeController : Controller
        {
            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" }
            };
    
            public ActionResult Index()
            {
                Pokemon p = new Pokemon();
                SelectList sl = new SelectList(pokeTypes, dataValueField: "typeId", dataTextField: "pokeType", selectedValue: 4);
                TempData["typeId"] = sl;
                TempData.Keep();
                return View();
            }
    
            [HttpPost]
            public string Index(Pokemon p)
            {
                string isLegendary = "";
                if (p.isLegendary)
                {
                    isLegendary = "Yes";
                }
                else
                {
                    isLegendary = "No";
                }
                var type = pokeTypes.Find(t => t.typeId == p.typeId).ToString();
                string s = $"Name: {p.name}  <br>Height: {p.height} cm <br>Id: #{p.number}  <br>Type: {type}  <br>Is Legendary: {isLegendary}";
                return s;
            }
        }
    

    Result:

    Best Regards,

    Jiadong Meng

    • Marked as answer by Anonymous Thursday, October 7, 2021 12:00 AM
    Thursday, October 17, 2019 3:06 AM
  • User-250884976 posted

    It Works, Can you please Explain me this var type = pokeTypes.Find(t => t.typeId == p.typeId).ToString(); line of code? thank you.

    Thursday, October 17, 2019 4:10 AM
  • User-17257777 posted

    Hi slalithp,

    This is a lambda expression. The lambda operator => divides a lambda expression into two parts. The left side is the input parameter and the right side is the lambda body. Here we use Lambda expression in a query. It means selecting the first element in the List(pokeTypes) which typeId equals to p.typeId, then using ToString() method to return the pokeType since you have overriden it. 

    For more details, you can refer to:

    https://docs.microsoft.com/en-us/dotnet/csharp/programming-guide/statements-expressions-operators/how-to-use-lambda-expressions-in-a-query

    https://www.c-sharpcorner.com/UploadFile/bd6c67/lambda-expressions-in-C-Sharp/

    Best Regards,

    Jiadong Meng

    Thursday, October 17, 2019 5:52 AM
  • User-250884976 posted

    Thank you <g class="gr_ gr_27 gr-alert gr_spell gr_inline_cards gr_run_anim ContextualSpelling" id="27" data-gr-id="27">jiadongm</g> :) 

    Thursday, October 17, 2019 6:53 AM