2 Replies - 994 Views - Last Post: 28 June 2016 - 07:57 AM

#1 trickstar34  Icon User is offline

  • D.I.C Head

Reputation: 3
  • View blog
  • Posts: 81
  • Joined: 05-June 09

Accessing Database Without Making Model

Posted 22 November 2015 - 06:30 PM

So for the first time I have been tasked with making a ASP.Net MVC application from scratch. I am pretty much asked to make a registration form, make the data for each registration on the home page (like a catalog), and have the data display in detail on a page generated when you click for more details.

So I followed this tutorial to make a registration system:
http://demo.dotnetaw...on-form-in-mvc4

and ended up with this code:

Registration CHTML:
@model Webpage.BizUserInfo
@{
    ViewBag.Title = "Register Business";
}
<style type="text/css">
    .field-validation-error {
        color: red;
    }
</style>
<div class="content">

@{
    var db = Database.Open("");
    var selectQueryString = "SELECT * FROM Product ORDER BY Name";
}

    <div class="row">
        <div class="col-sm-4 col-sm-offset-4">
            <div class="page-title">
                <h1>Register</h1>
            </div><!-- /.page-title -->

            @using (Html.BeginForm())
            {
                @Html.ValidationSummary(true)

                <fieldset>
                    @Html.AntiForgeryToken()
                    @if (ViewBag.Message != null)
                    {
                       <!-- <div style="border:solid 1px green">
                            @ViewBag.Message
                        </div> -->
                    }
                    <div class="form-group">
                        <label for="login-form-email">E-mail</label>
                        @Html.EditorFor(model => model.userEmail, new { htmlAttributes = new { @class = "form-control" } })
                        @Html.ValidationMessageFor(model => model.userEmail)
                    </div><!-- /.form-group -->

                    <div class="form-group">
                        <label for="login-form-first-name">First name</label>
                        @Html.EditorFor(model => model.nameFirst, new { htmlAttributes = new { @class = "form-control" } })
                        @Html.ValidationMessageFor(model => model.nameFirst)
                    </div><!-- /.form-group -->

                    <div class="form-group">
                        <label for="login-form-last-name">Last name</label>
                        @Html.EditorFor(model => model.nameLast, new { htmlAttributes = new { @class = "form-control" } })
                        @Html.ValidationMessageFor(model => model.nameLast)
                    </div><!-- /.form-group -->
                    <div class="form-group">
                        <label for="login-form-password">Password</label>
                        @Html.EditorFor(model => model.authentication_code, new { htmlAttributes = new { @class = "form-control" } })
                        @Html.ValidationMessageFor(model => model.authentication_code)
                    </div><!-- /.form-group -->

                    <div class="form-group">
                        <label for="login-form-password-retype">Confirm password</label>
                        @Html.EditorFor(model => model.ConfirmPassword, new { htmlAttributes = new { @class = "form-control" } })
                        @Html.ValidationMessageFor(model => model.ConfirmPassword)
                    </div><!-- /.form-group -->
                    <div class="form-group">
                        <label for="login-form-business-name">Business Name</label>
                        @Html.EditorFor(model => model.bizName, new { htmlAttributes = new { @class = "form-control" } })
                        @Html.ValidationMessageFor(model => model.bizName)
                    </div><!-- /.form-group -->
                    <div class="form-group">
                        <label for="login-form-business-address">Business Address</label>
                        @Html.EditorFor(model => model.bizAddress, new { htmlAttributes = new { @class = "form-control" } })
                        @Html.ValidationMessageFor(model => model.bizAddress)
                    </div><!-- /.form-group -->
                    <div class="form-group">
                        <label for="login-form-business-website">Business Website</label>
                        @Html.EditorFor(model => model.bizWebsite, new { htmlAttributes = new { @class = "form-control" } })
                    </div><!-- /.form-group -->
                    <div class="form-group">
                        <label for="login-form-business-about">Business Details</label>
                        @Html.EditorFor(model => model.bizAbout, new { htmlAttributes = new { @class = "form-control" } })
                    </div><!-- /.form-group -->

                    <input type="submit" class="btn btn-primary pull-right" value="Register" />
                    </fieldset>
                    }

Registration Controller:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using System.ComponentModel.DataAnnotations;

namespace Webpage.Controllers
{
    public class RegisterBizController : Controller
    {
        // GET: RegisterBiz
        public ActionResult RegisterBiz()
        {
            return View();
        }
        [HttpPost]
        [ValidateAntiForgeryToken]
        public ActionResult RegisterBiz(BizUserInfo U)
        {
            if (ModelState.IsValid)
            {
                using (RegisterBizModel dc = new RegisterBizModel())
                {

                    //you should check duplicate registration here 
                    dc.BizUserInfoes.Add(U);
                    dc.SaveChanges();
                    ModelState.Clear();
                    U = null;
                    ViewBag.Message = "Successfully Registration Done";
                }
            }
            return View(U);
        }
    }
}


Database model:
namespace Webpage
{
    using System;
    using System.Collections.Generic;
    using System.ComponentModel.DataAnnotations;
    using System.Web.Mvc;

    public partial class BizUserInfo
    {
        public int UserID_biz { get; set; }
        [RegularExpression(@"^([0-9a-zA-Z]([\+\-_\.][0-9a-zA-Z]+)*)[email protected](([0-9a-zA-Z][-\w]*[0-9a-zA-Z]*\.)+[a-zA-Z0-9]{2,3})$",
                    ErrorMessage = "Please provide valid email")]
        public string userEmail { get; set; }
        [Required(ErrorMessage= "Please provide First Name", AllowEmptyStrings= false)]
        public string nameFirst { get; set; }
        [Required(ErrorMessage = "Please provide Last Name", AllowEmptyStrings = false)]
        public string nameLast { get; set; }
        [Required(ErrorMessage = "Please provide Password", AllowEmptyStrings = false)]
        [DataType(System.ComponentModel.DataAnnotations.DataType.Password)]
        [StringLength(50, MinimumLength = 8, ErrorMessage = "Password must be 8 char long.")]
        public string authentication_code { get; set; }
        [System.ComponentModel.DataAnnotations.Compare("authentication_code", ErrorMessage = "Confirm password does not match.")]
        [DataType(System.ComponentModel.DataAnnotations.DataType.Password)]
        public string ConfirmPassword { get; set; }
        [Required(ErrorMessage= "Please provide Business Name", AllowEmptyStrings= false)]
        public string bizName { get; set; }
        [Required(ErrorMessage= "Please provide Business Address", AllowEmptyStrings= false)]
        public string bizAddress { get; set; }
        public string bizWebsite { get; set; }
        [DataType(System.ComponentModel.DataAnnotations.DataType.MultilineText)]
        public string bizAbout { get; set; }
    }
}


That code does work to register the users and their data to the database, but I want to use the data on the homepage using @{
var db = Database.Open("");
var selectQueryString = "SELECT * FROM Product ORDER BY Name";
}
but Visual Studio is reading "Database" as though it is a model and won't let me access the database like that. How can I access the information added to the database on my registration page on another page in the MVC site? It's really confusing and Google searches yield results that require huge drawn out processes I think can't be necessary (otherwise why on earth would someone choose this programming style?). I just want to access the tables generated in the database from the registration form and display the data on other pages easily. This is my first time working with MVC so bear with me if this is something trivial. Thanks in advance for any help.

This post has been edited by trickstar34: 22 November 2015 - 06:32 PM


Is This A Good Question/Topic? 0
  • +

Replies To: Accessing Database Without Making Model

#2 IngeniousHax  Icon User is offline

  • |>|20-514<|{3|2

Reputation: 84
  • View blog
  • Posts: 1,385
  • Joined: 28-March 09

Re: Accessing Database Without Making Model

Posted 28 June 2016 - 07:49 AM

To start, your entire approach to ASP.NET MVC is wrong. The purpose of the MVC design pattern is to create a clear separation of the Presentation, Data, and Logic Layer. You're mixing the Presentation and the Data Layer while attempting to completely axe the Logic Layer. Don't do this. Developers coming in behind you will be hunting you down for, what I assume, would be a majority of your life. Instead, just use the framework as it was designed. Create a model (you already have it, just use it).

In your controller, you would have some Controller Action methods like "Index", "Details", etc... Whatever needs you have. You then create an HttpGet and; if you're POSTing stuff; an HttpPost controller action method.
[HttpGet]
public ActionResult Details(int id) { }



Once you have a basic controller Action Method, you need to make it do something. Get the data from the database, perform some magic, return it to the view.

[HttpGet]
public ActionResult Details(int id) 
{ 
    using(var context = new YourDatabaseContext())
	{
		BizUserInfo userInfo = context.Where(x => x.id == id).FirstOrDefault();
		
		if(userInfo == null)
		{
			return RedirectToAction("Error", "ControllerName");
		}
		
		return View(userInfo);
	}
}



That's all it takes. Assuming you have a DbContext derived class (where your DbSet<BizUserInfo> bizUserInfo {get; set;} resides)
Was This Post Helpful? 0
  • +
  • -

#3 modi123_1  Icon User is online

  • Suitor #2
  • member icon



Reputation: 13401
  • View blog
  • Posts: 53,498
  • Joined: 12-June 08

Re: Accessing Database Without Making Model

Posted 28 June 2016 - 07:57 AM

This is also an 8+ month old topic where the post hasn't returned since then either. Just say'n - watch those post dates.
Was This Post Helpful? 0
  • +
  • -

Page 1 of 1