Pavan
Pavan

Reputation: 61

Displaying model assigned name in View Mvc3

This is my View

@

using (Html.BeginForm("Display", "Home", @FormMethod.Post))
    {
    <div>Name:<a>@ViewBag.st</a><br /></div>
       <a></a>
    <div>City:<a>America</a></div>
    <br />
     <input type="submit" value="Submit" /> 
    <br />
    }

THis is model class

public class User { private string m_name = string.Empty;

public string Name
{
    get
    {
        return m_name;
    }
    set
    {
        m_name = value;
    }
}

}

This is my controller class

[HttpGet]
         public ActionResult Viewdetails()
         {
            User ur=new User();
            ur.Name = "Danny";
            ViewBag.st = ur.Name;
           return View();
         }

        [HttpPost, ActionName("Viewdetails")]
        public ActionResult Test()
        {
            return View();
        }
         [HttpPost]
         public ActionResult Display()
         {
             return View();
         }
    }

Now how to display Danny in my view in my Viewdetails.cshtml instead of using

@Viewbag

Upvotes: 0

Views: 508

Answers (1)

Darin Dimitrov
Darin Dimitrov

Reputation: 1039398

You could use an input field so that when the form is submitted its value is sent to the Display action. Also let's clean a little bit your code and get rid of ViewBag.

So you have a model which is fine:

public class User
{
    public string Name { get; set; }
}

Then you could have a controller with 2 actions - one that populates the model and passes it to the Viewdetails.cshtml view and another action which is invoked when the form is submitted and renders the Display.cshtml view:

public class HomeController: Controller
{
    [HttpGet]
    public ActionResult Viewdetails()
    {
        User ur = new User();
        ur.Name = "SravanKumar";
        return View(ur);
    }

    [HttpPost]
    public ActionResult Display(User ur)
    {
        return View(ur);
    }
}

and then inside your Viewdetails.cshtml view you would use the model to render an input field instead of a link:

@model User
@using (Html.BeginForm("Display", "Home", FormMethod.Post))
{
    <div>Name: @Html.EditorFor(x => x.Name)</div>
    <div>City: Secunderabad</div>
    <br />
    <input type="submit" value="Submit" /> 
}

and inside your Display.cshtml view:

@model User
<div>Thanks for choosing the name: @Model.Name</div>

Upvotes: 4

Related Questions