Вопрос

I have a problem with getting/handling POST data from <form> in ASP.NET MVC 4 Razor project.

What have I done?

Don't argue at my code, I'm only testing ASP.NET MVC 4 features.

As you can see in the controller's code, I've done also a Model for user info:

public class AuthForm
{
    public string Login { get; set; }
    public string Password { get; set; }
}

I thought, that ASP.NET if the model is correct will automatically parse data into the model, but mistaken.

Then I tried to use .Request["name"], but (inputs weren't empty):

enter image description here

Also I've tried to use such Attributes:

  • [HttpPost]
  • [AcceptVerbs(HttpVerbs.Post)]

But also no success!

What did I wrong? Please, help me to fix my issues.

Thanks

Это было полезно?

Решение

You need to use the helper methods so that MVC knows how to bind the values and then in the controller you will be able to use the model (as the model binder will figure it out for you)

e.g.

@model Models.AuthForm
@{
    ViewBag.Title = "СЭЛФ";
}
@section home {

@using (Html.BeginForm("Auth", "Controller")) {
    <div class="control-group">
        @Html.LabelFor(model => model.Login, new { @class = "control-label" })
        <div class="controls">
            @Html.TextBoxFor(model => model.Login, new { @class = "input-large", autocapitalize = "off" }) 
            @Html.ValidationMessageFor(model => model.Login, "*", new { @class = "help-inline" })
       </div>
    </div>

    <div class="control-group">
        @Html.LabelFor(model => model.Password, new { @class = "control-label" })
        <div class="controls">
            @Html.PasswordFor(model => model.Password, new { @class= "input-large" }) 
            @Html.ValidationMessageFor(model => model.Password, "*", new { @class = "help-inline" })
        </div>
    </div>
    <div class="form-actions">
         <input type="submit" class="btn btn-primary" value="Log On" />
    </div>
}
}

Using the native HTML controls is an option but you'll need to do it in the same way as the helper methods above otherwise the model won't be populated.

Лицензировано под: CC-BY-SA с атрибуция
Не связан с StackOverflow
scroll top