Mandar Jogalekar
Mandar Jogalekar

Reputation: 3281

Pass values from view to controllers

I am starting off with mvc framework and trying to do some things. One of them to create simple registration page which has few textboxes and passes values to controller which in turn saves to database.

I have used form posting method to achieve similar task

  @using (Html.BeginForm())
    {
        @Html.Label("Username:") @Html.TextBox("texbotUserName", "") <br />
        @Html.Label("Password:") @Html.TextBox("texbotPassword", "") <br />

        <input type="submit" value="SignIn" name="action:SignIn" /> 
        <input type="submit" value="Register" name="action:Register" /> 
    }

    [HttpPost]
    [MultiButton(Name = "action", Argument = "SignIn")]
    public ActionResult SignIn(string textboxUserName)
    {
        return Content(textboxUserName);
    }

Apart from above, Is there a better way to pass values (using models maybe?) as per best practices stuff.

Thanks for answers.

Upvotes: 1

Views: 1196

Answers (1)

Jatin patil
Jatin patil

Reputation: 4288

Designing the model :

public class UserLoginModel 
{ 
    [Required(ErrorMessage = "Please enter your username")] 
    [Display(Name = "User Name")]
    [MaxLength(50)]
    public string UserName { get; set; }
    [Required(ErrorMessage = "Please enter your password")]
    [Display(Name = "Password")]
    [MaxLength(50)]
    public string Password { get; set; } 
} 

Presenting the model in the view :

@model MyModels.UserLoginModel
@{
    ViewBag.Title = "User Login";
    Layout = "~/Views/Shared/_Layout.cshtml";
 }
@using (Html.BeginForm())
{
    <div class="editor-label">
    @Html.LabelFor(m => m.UserName)
    </div>
    <div class="editor-field">
    @Html.TextBoxFor(m => m.UserName)
    @Html.ValidationMessageFor(m => m.UserName)
    </div>
    <div class="editor-label">
    @Html.LabelFor(m => m.Password)
    </div>
    <div class="editor-field">
    @Html.PasswordFor(m => m.Password)
    @Html.ValidationMessageFor(m => m.Password)
    </div>
    <p>
    <input type="submit" value="Log In" />
    </p>
   </div>
} 

Working with Action

[HttpPost]
public ActionResult Login(UserLoginModel user)
{
     // Implementation
     return View(user);
} 

Upvotes: 1

Related Questions