0

This should be a very easy question as I'm a noob and almost have it figured out myself. I'm authenticating against info in a database and I want to simply display the row's data to the view. I'm really not sure how to, I'm assuming, create a variable in the controller that has the row's data and call that variable to the view so that I can see the rows information on the screen.

Thanks everyone, hope to get better at this soon!

My Model:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.ComponentModel.DataAnnotations;
namespace Mybasicvalidator.Models
{
public class Class1
    {
    [Required]
    public int id { get; set; }
    public string fname {get; set;}
    public string lname { get; set; }
    public string email { get; set; }
    public string username { get; set; }
    public string password { get; set; }
    }
}

My Controller:

using Mybasicvalidator.Models;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using System.Web.Security;
namespace Mybasicvalidator.Controllers
{
public class homeController : Controller
{
    //
    // GET: /home/
    [HttpGet]
    public ActionResult Index()
    {
        return View();
        return Content("Login Page");
    }
    [HttpPost]
    public ActionResult Index(Class1 modelle)
    {
        if (ModelState.IsValid)
        {
            if (DataAccess.DAL.CheckUser(modelle.fname))

            {
            return RedirectToAction("Index", "profile");
            }

            {
                return Content("FAIL");
            }
        }
        return View();
    }
}
}

MY Data Access Layer (DAL):

using System;
using System.Collections.Generic;
using System.Configuration;
using System.Data.SqlClient;
using System.Linq;
using System.Web;


namespace Mybasicvalidator.DataAccess
{
    public class DAL
    {
    static SqlConnection conn = new SqlConnection(ConfigurationManager.ConnectionStrings["MyConnectionString"].ToString());

    public static bool CheckUser(string fname) 
    {
        bool authenticated = false;

        string query = string.Format("SELECT * FROM [tbl_user] WHERE fname = '{0}'", fname);

        SqlCommand cmd = new SqlCommand(query, conn);
        conn.Open();
        SqlDataReader sdr = cmd.ExecuteReader();
        authenticated = sdr.HasRows;

          conn.Close();
        return (authenticated);
    }

}
}

So I know that it is reading the row and checking the authentication against my row, so how do I bring the data row to the view? I'm very new to this and have tried for a week to get it going, so I would appreciate some code I can follow.

Thanks again

Batsu
  • 55
  • 1
  • 4
  • 10

2 Answers2

0

You are leaving out the ViewModel.

In an MVC application:

  • The Controller selects the correct view, constructs the view model, and then passes it to the view.
  • The View Model contains the information/data that the view will display.
  • The View contains the markup that actually displays the data from the ViewModel.

Controller:

[HttpGet]
public ActionResult Index(int userId)
{
    return View(new UserViewModel(userId));
}

View Model:

public class UserViewModel { 
   public UserViewModel(int userId) {
      UserToDisplay = UserRepository.GetUserById(userId);
   }

   public User UserToDisplay { get; set; }
}

View:

@model UserViewModel;

Hello @model.UserToDisplay.FirstName!
Heather
  • 2,602
  • 1
  • 24
  • 33
  • Hi Heather, I placed the 'View Model' code in the Model folder's Class1.cs file, but 'UserRepository' doesn't exist in the current context. Neither does 'User' :( – Batsu Jan 17 '13 at 21:54
  • "UserRepository" and "User" are ficticious classes used for this example. Replace them with whatever repository you're using and whatever class you want to display. – Heather Jan 17 '13 at 22:07
0

You could have your DAL method return the model:

public class DAL
{
    public static Class1 GetUser(string fname) 
    {
        var connectionString = ConfigurationManager.ConnectionStrings["MyConnectionString"].ToString();
        using (var conn = new SqlConnection(connectionString))
        using (var cmd = conn.CreateCommand())
        {
            conn.Open();
            cmd.CommandText = "SELECT * FROM [tbl_user] WHERE fname = @fname";
            cmd.Parameters.AddWithValue("@fname", fname);
            using (var reader = cmd.ExecuteReader())
            {
                if (!reader.Read())
                {
                    return null;
                }

                var user = new Class1();
                user.id = reader.ReadInt32(reader.GetOrdinal("id"));
                user.fname = reader.ReadString(reader.GetOrdinal("fname"));
                ... and so on for the other properties
                return user;
            }
        }
    }
}

Notice how I used a parametrized query to avoid SQL injection which your code was vulnerable to.

And then the controller action which is performing the authentication you could emit a forms authentication cookie if success before redirecting:

[HttpPost]
public ActionResult Index(Class1 modelle)
{
    if (ModelState.IsValid)
    {
        var user = DataAccess.DAL.GetUser(modelle.fname);
        if (user != null)
        {
            FormsAuthentication.SetAuthCookie(modelle.fname, false);
            return RedirectToAction("Index", "profile");
        }
        return Content("FAIL");
    }
    return View(modelle);
}

and in your target controller action could now be decorated with the [Authorize] attribute as only authenticated users can access it:

public class ProfileController: Controller
{
    [Authorize]
    public ActionResult Index()
    {
        var user = DataAccess.DAL.GetUser(User.Identity.Name);
        return View(user);
    }
}

finally in the corresponding view:

@model Class1
<div>
    Hello @Html.DisplayFor(x => x.fname)
</div>
Darin Dimitrov
  • 1,023,142
  • 271
  • 3,287
  • 2,928