Search code examples
c#asp.net-mvcgetter-setter

C# Getter Setter in MVC


I made my website with the ViewBag, but from Java I know there are getter and setters for that. I know how I can create this getter and setter but I don't know how I can get the values in my CSHTML-File? I tried it with:

<p>Message1: @Model1.test</p>
<p>Message2: @Html.DisplayFor(model => model.test)</p>

Thanks for your help

Controller:

 public ActionResult Index()
    {
        Model1 model = new Model1();
        model.test = "Hallo Test!";
        return View();
    }

Model:

public string test { get; set; }

Solution

  • You should create a ViewModel.And put in View method as below

     public class Model
    {
        public int Id { get; set; }
    }    
    

    In your Action Method

    Model model = new Model();
    model.Id = 1;
    return View(model);  
    

    In you view

    @model ProjectName.Model'sFolderName.Model 
    

    You can use Model in your view now