ASP.NET MVC Thread

Hi guys I am not looking to do anything to complicated but nothing I try works. I am using ASP.NET MVC to make a website but I want to take input from a textbox. I have tried many different methods but an error occurs. All I want to do is have some HTML like this.

<label> Company Name </label>
				<input type="text" name="email" id="comp" r/>
				<button type ="submit" id="newUserButtonSQL" <button type ="button" id="newUserButton" onclick="location.href='@Url.Action("creatUser","Home")'">Create</button>>Login</button>

and then get the data like this in C#

public void creatUser(){
			string company = "rats";
			company = Request ["comp"].ToString ();
                    ..do stuff}

Is that the extent of your code? You've got a few issues with it such as a button within a button. MVC is framework (Model View Controller). The model contains the bits of data you need, the View is what you see on the screen like the form and the Controller does the work.

For a simple Textbox form, your "CreateCompany" View (the CreateCompany.cshtml file) would contain something like this:

<form action="/home/createcompany" id="createCompany" method="post">
   <input id="companyName" name="companyName" placeholder="Company Name" type="text" value="">                                    
   <button type="submit">Create Company</button>
</form>

And your methods in your home controller would look something like this (note that you Post method parameters need to equal the name part of your View form controls so their values get marshalled from the form submit into them):

[HttpGet]
public ActionResult CreateCompany() 
{
	return View();
}

[HttpPost]
public ActionResult CreateCompany(string companyName) 
{
	if (ModelState.IsValid)
        {
		if (!string.IsNullOrEmpty(companyName) 
		{
			// Do your CRUD work here
		}
	}

	return View();
}

The HttpGet part just displays the CreateCompany View when you first go to the URL such as http://www.mywebserver.com/home/CreateCompany and the HttpPost part deals with the form submit.
The ModelState.IsValid would be used if you were passing through a model (you can do lots of clever annotation stuff to ensure you're not getting duff data through) rather than just a string and probably isn't needed in such a simple example as this, so can be ignored.
The string.isnullorempty is just making sure you've got something to add
The return view then returns the CreateCompany view back to the user.

1 Like

Thanks I am a total noob at this, I am trying to do this on MonoDevelop on Linux so I have had to do some strange stuff like write a c++ program to exchange info from a MySQL database because I could not get the connector for .NET on Linux. After I get done with this I should probably get a VM with windows on top of my Linux system.

You shouldn't need to be writing c++ stuff to use the MySQL database library under Mono: http://www.mono-project.com/docs/database-access/providers/mysql/

I went to that site and did the sudo gacutil -i MySql.Data.dll part but MonoDevelop still cannot find the namespace of using MySql.Data.MySqlClient;

editing due to Google clarification

You'll need to add the reference to the project in order for you to be able to use the Using.

well I was able to add it to my project and now it knows what using MySql.Data.MySqlClient; but it does not know what IDbConnection dbcon; is still.

Is IDbConnection further down the MySql.Data.MySqlClient rabbit hole?

Is there anything in MonoDeveloper like in VisualStudio where if you click on IDbConnect and his a shortcut key it will ask you to add the appropriate using for that class?

Sorry, I am not familiar with MySQL.

well turns out if you right click in Mono there is an option to resolve the conflict by adding the dependency. It now looks like my C++ program will have to be put to rest lol.

IDbConnection isn't part of the MySQL library, that's part of System.Data - is there any particular reason you are using an interface rather than instantiating the concrete MySqlConnection class?

1 Like

That link you posted brought me here
http://www.mono-project.com/docs/database-access/providers/mysql/

Ah, stupid me. Should have noticed that.

I hadn't read that far down the page.

It'll work fine, I'm not entirely sure why they've done that in the example tbh and the code is not particularly clean, I'd be wrapping the instantiations inside a using block with the concrete classes - but that's the joys of coding, plenty of different ways of doing the same task :)

I have been kind of busy but I have another chance now to work on the site again but I get this exception

 at MySql.Data.MySqlClient.MySqlStream.ReadPacket () [0x00096] in <filename unknown>:0 
  at MySql.Data.MySqlClient.NativeDriver.ReadPacket () [0x00000] in <filename unknown>:0 
  at MySql.Data.MySqlClient.Authentication.MySqlAuthenticationPlugin.ReadPacket () [0x00000] in <filename unknown>:0

my code looks like

    [HttpPost]
		public ActionResult creatUser(string companyName){
			if(ModelState.IsValid){
				if(!string.IsNullOrEmpty(companyName)){
					string company = companyName;
					string cell = "6414";
					string phone = "641521";
					string password = "test";
					string email = "[email protected]";
					string connectionString = 
						"Server=localhost;" +
						"Database=test;" +
						"User ID=shane;" +
						"Password="cat" +
						"Pooling=false";
					string sqlCommand = "INSERT INTO COMPANIES VALUES ('" + company + "','" + cell + "','" + phone + "','" + password + "',NULL,'" + email + "');";
					Console.WriteLine (sqlCommand);
				
					MySqlConnection conn = new MySqlConnection (connectionString);
					conn.Open ();
					MySqlCommand comm = conn.CreateCommand ();
					comm.CommandText = sqlCommand;
					comm.ExecuteNonQuery ();
					//IDbCommand dbcmd = dbcon.CreateCommand ();
					//Process p = new Process ();
					//p.StartInfo.FileName = "/home/shanedrafahl/project/Iowa_State_Fair_OrderingSystem/CppMiddleMan/cppsql";
					//p.StartInfo.Arguments = "0 " + phone + " 0 " + company + " " + cell + " " + password + " " + email;
					//p.StartInfo.UseShellExecute = false;
					//p.StartInfo.RedirectStandardOutput = true;
					//p.Start();
					//p.WaitForExit ();

				}
			}
			return View ();
		}

At what point is it failing? On the connection open or on the command execute?

Also, you should really be using SqlParameter objects on your command object rather than building the SQL as a string, doing it like that leaves you wide open to SQL injection so is considered bad practice.

1 Like

nvm I got it to work but thanks for responding lol

No worries, but I would take a look at SqlParameters, you'd want something like

MySqlCommand sqlCommand = new MySqlCommand("INSERT INTO COMPANIES (Company, Cell, Phone, Password, Email) VALUES  (@Company, @Cell, @Phone, @Password, @Email)", conn);
sqlCommand.Parameters.Add(new MySqlParameter("@Company", company));
sqlCommand.Parameters.Add(new MySqlParameter("@Cell", cell));
sqlCommand.Parameters.Add(new MySqlParameter("@Phone", phone));
sqlCommand.Parameters.Add(new MySqlParameter("@Password", password));
sqlCommand.Parameters.Add(new MySqlParameter("@Email", email));

Or have a stored proc in your database and calling that in your command object with MySqlParameters

I may look into doing something like that but while you are here would you know how to create like to edit text from a view from the C# code. I want to create like a message if the user does not enter all the required fields.

You can do that by using a Model object and annotating the Model properties:

So, create a model for your Company form page

    public class CompanyVM
    {
        [Required(ErrorMessage = "You must enter a company")]
        public string company { get; set; }   
    }

And on your View you'll need to add this somewhere that the error messages will go into

                    @Html.ValidationSummary()

You'll need to change your post method in your controller to accept the model as the parameter

public ActionResult creatUser(CompanyVM vm) 
{
    if (ModelState.IsValid) 
   {
      // Do valid stuff
   }

   return View(vm);
}

You'll need to add a using System.ComponentModel.DataAnnotations to your model class. You can add as many properties as you like to a ViewModel, but the property names will need to match the name of your HTML controls on your view form to get them to populate when the form is submitted - you can do all sorts of clever annotation, so look up MVC Data Annotations if you want to know more about it.

Oh and you'll need to add a @model CompanyVM at the top of the View page and change your HttpGet controller method to include the ViewModel too

[HttpGet]
public ActionResult creatUser() 
{
 CompanyVM vm = new CompanyVM();
return View(vm);
}
1 Like

I was able to change the function creatUser to use the viewModel and it can send data to the Database but the warning does not come up if I dont enter anything. I think it still sends the command to MySQL but I know the data must be still going through the model because I am creating the command string from data from the model.

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using System.Web.Mvc.Ajax;
using System.Diagnostics;
using MySql.Data.MySqlClient;
using FairOrderingSystem;

//http://stackoverflow.com/questions/878632/best-way-to-call-external-program-in-c-sharp-and-parse-output
//https://forum.teksyndicate.com/t/asp-net-mvc-text-box/106790/12
using System.Data;

namespace Fair.Controllers
{
	public class HomeController : Controller
	{

		public ActionResult Index ()
		{

			var mvcName = typeof(Controller).Assembly.GetName ();

			var isMono = Type.GetType ("Mono.Runtime") != null;

			ViewData ["Version"] = mvcName.Version.Major + "." + mvcName.Version.Minor;
			ViewData ["Runtime"] = isMono ? "Mono" : ".NET";

			return View ();
		}

		public ActionResult NewUser(){
			return View ();
		}
		public ActionResult LoginS(){
			return View ();
		}

		[HttpPost]
		public ActionResult creatUser(FairOrderingSystem.Models.Company comp){
			if(ModelState.IsValid){
				if(ModelState.IsValid){
					string company = comp.companyName;
					string Cell = comp.cell;
					string Phone = comp.phone;
					string Password = comp.password;
					string Email = comp.email;

					string connectionString = 
						"Server=localhost;" +
						"Database=fair;" +
						"User ID=shane;" +
						"Password=text;" +
						"Pooling=false";
					string sqlCommand = "INSERT INTO COMPANIES VALUES ('" + company + "','" + Cell + "','" + Phone + "','" + Password + "',NULL,'" + Email + "');";
					MySqlConnection conn = new MySqlConnection (connectionString);
					conn.Open ();
					MySqlCommand comm = conn.CreateCommand ();
					comm.CommandText = sqlCommand;
					comm.BeginExecuteNonQuery ();

				}
			}
			return View (comp);
		}
		[HttpGet]
		public ActionResult creatUser(){
			FairOrderingSystem.Models.Company comp = new FairOrderingSystem.Models.Company ();
			return View (comp);
		}
	}
}


@model IEnumerable<FairOrderingSystem.Models.Company>
@{
	ViewBag.Title = "New User";

}

@Html.ValidationSummary()
<hCompanyd>
    <title></title>
</head>
<body>
	<div>
		<h1>
			Please Enter the Info Bellow 
		</h1>
	</div>
	<div class="inputArea">

			
			<form action="/Home/creatUser" id="createCompany" method="post">
				<input id="companyName" name="companyName" placeholder="Company Name" type ="text" >
				<input id="cell" name="cell" placeholder="cell" type="text" > 
				<input id="phone" name="phone" placeholder="phone" type="text" >
				<input id="password" name="password" placeholder="password" type="password">
				<input id="confirmpassword" name="confirmpassword" placeholder="confirm password" type="password">
				<input id="email" name="email" placeholder="email" type="text" >
				<button type="submit">Create</button>
			</form>
			 
	</div>
	<p>
		
	</p>
    <div>
    
    </div>
</body>
</html>