Object Model Properties Not Assigned After Submitting The Form

I have view with UserSample model with two properties (Username, Password), All I want to achieve is to take these values from the textboxes and to store them into the object model and then in the Action method to take this object and manipulate it.

But here in this code the object properties in the action method Index are always null after submitting the form with filled text box fields.

Controller:

public ActionResult Index(UserSample user) //this is the object which properties I want to be asigned.
        {
            if (user != null)
            {

            }

            return View();
        }

View:

@using (@Html.BeginForm("Index","Login"))
{
    <table>
        <tr>
            <td>Username: </td>
            <td>@Html.TextBox("Username")</td>
        </tr>
        <tr>
            <td>Password: </td>
            <td>@Html.TextBox("Password")</td>
        </tr>
        <tr>
            <td></td>
            <td><input id="btnSubmit" type="submit" value="Submit" /></td>
        </tr>
    </table>
}

Answers


Try adding this line to your view:

@model UserSample

You probable need to include the namespace there. MyApp.Models.UserSample for example.

Then you can use stronly typed html-helpers:

<td>@Html.TextBoxFor(model => model.UserName)</td>

and

<td>@Html.TextBoxFor(model => model.Password)</td>

You should decorate the Index(UserSample user) method with the HttpPost attribute:

public ActionResult Index()
{
    // Get method.
    UserSample model = new UserSample();
    return View(model);
}

[HttpPost]
public ActionResult Index(UserSample user)
{
    //  POST method.
}

When you post the form now, the UserSample object should be populated with the values from the form.

If you don't understand model binding, I suggest you look into it. This tutorial might get you started.


Need Your Help

Html ordered list 1.1, 1.2 (Nested counters and scope) not working

html css

I use Nested counters and scope to create a html ordered list.

Does cloning in angular-dragdrop work?

angularjs jquery-ui-droppable

The angular-dragdrop examples contain the following example:

About UNIX Resources Network

Original, collect and organize Developers related documents, information and materials, contains jQuery, Html, CSS, MySQL, .NET, ASP.NET, SQL, objective-c, iPhone, Ruby on Rails, C, SQL Server, Ruby, Arrays, Regex, ASP.NET MVC, WPF, XML, Ajax, DataBase, and so on.