开发者

HOw to access the hidden value set in cshtml from controller?

开发者 https://www.devze.com 2023-04-06 11:22 出处:网络
Can i have something like this i开发者_运维技巧n my cshtml @Html.hiddenfor(model => model.name , \"passname\")

Can i have something like this i开发者_运维技巧n my cshtml

@Html.hiddenfor(model => model.name , "passname")

In controller :

i want to access this modal.name which will be having the value i set i.e "passname"


2 ways:

1 - your model has to have this property that it can pass to HiddenFor. For example

class

class PageModel{
   public string HiddenFieldValue{get;set;}
   public string Name {get;set;}
}

in cshtml

@model PageModel
...
@Html.hiddenfor(model => model.name, model.HiddenFieldValue)

in controller

public ViewResult MyPage(){
    return View(new PageModel(){
        HiddenFieldValue = "Hello World!";
    });
}

2nd way: pass in through ViewBag/ViewData.

in controller

public ViewResult MyPage(){
    ViewBag.HiddenFieldValue = "Hello World!";
    return View();
}

in cshtml

@model PageModel
...
@Html.hiddenfor(model => model.name, ViewBag.HiddenFieldValue)


The value for the hidden field will be send together with all the other POST data (if your form uses a POST).

So you can:

  1. Add a property "passname" to the model that you use to retrieve the data.
  2. Create an argument named "passname" on the action that handles the post.
  3. Add a FormCollection to the argement (on the action that handles the post), and retrieve the value from there.
  4. Get it from the Request using Request.Form["passname"] or event Request["passname"]

    // Example 1
    
    public class MyModel {
       // other properties
    
       public string passname { get; set; }
    }
    
    public class MyController : Controller {
         [HttpPost]
         public ActionResult MyAction(MyModel data) {
         }
    }
    
    // Example 2
    
    public class MyController : Controller {
       [HttpPost]
       public ActionResult MyAction(string passname) {
       }
    }
    
    // Example 3
    
    public class MyController : Controller {
       [HttpPost]
       public ActionResult MyAction(FormCollection data) {
            var passname = data["passname"];
       }
    }
    
    // Example 4
    
    public class MyController : Controller {
       [HttpPost]
       public ActionResult MyAction() {
            var passname = Request.Form["passname"];
       }
    }
    
0

精彩评论

暂无评论...
验证码 换一张
取 消