Как авторизовать пользователя с главной страницы форума? - PullRequest
0 голосов
/ 22 сентября 2011

Я пытаюсь реализовать простой блог, который содержит темы

Модели / Topic.cs

public class Topic
{
    public int ID {get; set;}

    [StringLength(50)]
    [RequiredAttribute(ErrorMessage = "*")]
    public string Title {get; set;}

    [StringLength(1024)]
    [RequiredAttribute(ErrorMessage = "*")]
    public string Body { get; set; }

    public int CommentsCount { get; set; }

    public DateTime TimeLastUpdated { get; set; }
    public int AuthorID { get; set; }

    public virtual List<Comment> commentsList { get; set; }

}

Главная страница выглядит как список тем.

Контроллеры / HomeController.cs

public class HomeController : Controller

    private ContentStorage db = new ContentStorage();
    public ViewResult Index()
    {
        // Topics = DbSet<Topic> Topics { get; set; }
        return View(db.Topics.ToList());
    }

   [HttpPost]
   public void LogIn(string login, string password)
   {
        int i;
        i = 10;

   }

}

Просмотр главной страницы очень прост.

Views / Home / Index

@model IEnumerable<MvcSimpleBlog.Models.Topic>
...
<table width="95%" height="86" border="0">
      <tr>
        <td width="45%" valign = "bottom" >Login:</td>
        <td width="45%" valign = "bottom" >Password:</td>
        <td width="10%"></td>
      </tr>

      <tr>
        <td width="45%"><p> <input type="text" name="login" />  </p></td>
        <td width="45%"><p><input type="password" name="password" /></p></td>
        <td width="10%" align = "left"> 
            @using (Html.BeginForm("LogIn", "Home"))
            { 
                <input type = "submit" value = "Enter" />
            }
        </td>
      </tr>

      <tr>
        <td width="45%" valign = "top" >@Html.ActionLink("Register", "Register", "Account")</td>
      </tr>

</table>

Как передать значения из полей редактирования в представлении методу HomeController? Метод «Вход в систему» ​​должен был получить данные из представления, вызвать контроллер «Учетная запись», передав ему логин и пароль пользователя. Контроллер «Аккаунта» должен проверить этого пользователя и перенаправить браузер на главную страницу с темами.

Но я не могу получить доступ к полям ввода логина и пароля в представлении ... и я действительно не знаю, что мне делать, и моя модель верна

1 Ответ

0 голосов
/ 22 сентября 2011

Эти поля ввода должны быть внутри вашего Html.BeginForm, если вы хотите, чтобы их значения были отправлены на сервер при отправке формы.В настоящее время у вас есть только одна кнопка отправки внутри формы.Итак:

@using (Html.BeginForm("LogIn", "Home"))
{
    <table width="95%" height="86" border="0">
        <tr>
            <td width="45%" valign="bottom">Login:</td>
            <td width="45%" valign="bottom">Password:</td>
            <td width="10%"></td>
        </tr>
        <tr>
            <td width="45%">
                <p>
                    <input type="text" name="login" />
                </p>
            </td>
            <td width="45%">
                <p>
                    <input type="password" name="password" />
                </p>
            </td>
            <td width="10%" align="left"> 
                <input type="submit" value="Enter" />
            </td>
        </tr>
        <tr>
            <td width="45%" valign="top">
                @Html.ActionLink("Register", "Register", "Account")
            </td>
        </tr>
    </table>
}

Теперь ваше действие контроллера LogIn может получить 2 значения в качестве параметров действия, например:

[HttpPost]
public ActionResult LogIn(string login, string password)
{
    ... perform authentication
}
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...