I am working on a group project using MVC and I am trying to get the Orders view to connect to our database which is on an offsite server.
The few tutorials I have seen concerning incorporating a database with a ASP.NET MVC project talks about adding the code
var db = Database.Open("nameofdatabases");
My problem is that when I start to type Database, the little drop down menu showing what options are available does not show it, DataBindings is the closest it gets.
Also, someone had showed us another line of code:
public VivaceContext db = new VivaceContext();
List<Distributor> list = new List<Distributor>();
public ActionResult Index()
{
var ist = db.TableName.FirstOrDefault(x => x.FieldName == "").Orders.ToList();
var i = db.TableName.Where(x => x.FieldName == "").ToList();
return View();
}
What I am needing to do is retrieve information from several tables in a database at a different location, add data, edit data, and delete data.
You Can do this Using Model.
Create a Context Class For Each and Every Database which you want to use.
Then Create Strongly Type Controller For your Table it will allowed to do all CRUD operation on that table.
Related
I have a new .NET Core application that is using Entity Framework Core. The query against the database returns no data.
The context is created like this:
private readonly ExtensionDataModel.DataSet1 _context = new ExtensionDataModel.DataSet1();
and the method using it is:
public ExtensionDetails GetExtensionDetails(string extension)
{
var users = _context.Users;//.Where(x=>x.activeFlag==true);//.Where(x => x.workPhone.Contains("7029"));
if (!users.Any())
{
return null;
}
var user = users.First();
var detail = new ExtensionDetails()
{
Extension = user.workPhone,
FirstName = user.firstName,
LastName = user.lastName,
Location = user.LocationsRow.LocationDesc
};
return detail;
}
I get no errors, and the users.Any returns false, even through there is data in the database. If I expand the users object in the debugger, and look at the result set, the result set is empty. Also, I have been unable to see the query that it is generating.
When I use SQL Server Profiler, it does not show any database activity.
When I go to the Entity Framework designer (clicking on DataSet1.xsd), I can right click on the users table and choose Preview Data, and it brings back the rows in the table.
I am using a separate SQL Server database server, and created the EF model by extracting it from the database.
My data model has two tables in it, and the user that I am using has only read access to those two tables.
Any help would be appreciated. I am new to .net core, but have been using EF for many years.
I want to create a model for a student in asp.net mvc and i want to know how i can include an image with the mode.
Is there any other way than just using the image DataURI?
My Goal is that I want to provide security so that images cannot be seen by others.
I am doing a project on ASP.Net MVC using MongoDB
I'm not sure what you're asking for. It is unclear to whom and where the image should be unavailable. But I'll try to give some hints. This will not be copy/"pastable" and needs to be adjusted to match your data/models.
I would separate the image from the model in mongo. I.e. The "Student model" should hold an Id to it's image which is stored in a collection of student images.
In your web page fetch the image via a controller action like this. If you want to hide it for all other users than the student itself then you need to just show it when the user match a certain criteria. I assume since you are talking about security that you have login (Identity) up and running.
#if (User.Identity.Name == #studentModel.UniqueName)
{
<img src="#Url.Action("GetStudentImage", "StudentController", new {id = studentModel.ImageId})"
}
In your controller you fetch the image from the mongo database. (This is just from the top of my head and will not match your models, so you would have to adjust)
public Task<ActionResult> GetStudentImage(string id)
{
var image = mongo.GetCollection<Image>("Image").AsQueryable().First(x => x.Id == id);
return File(image.ImageBytes.ToArray(), "image/png"); // the image in bytes
}
I'm currently developing a web app using the open source Kendo UI Scheduler with ASP.NET MVC Visual Studio 2012. But i'm experiencing some trouble while trying to connect my scheduler with a local database to store the bookings made by users of my application.
I've been looking for documentation to help me with this but I haven't been able to set this up entirely...
I followed instructions about this on: http://docs.telerik.com/kendo-ui/getting-started/using-kendo-with/aspnet-mvc/helpers/scheduler/ajax-editing
I've added the Entity Framework Data Model and necessary code in Models like TaskViewModel but the problem occurs in my Controllers.
public ActionResult Tasks_Read([DataSourceRequest]DataSourceRequest request)
{
using (var sampleDB = new SchedulerEntities())
{
IQueryable<TaskViewModel> tasks = sampleDB.Tasks.ToList().Select(task => new TaskViewModel()
{
TaskID = task.TaskID,
Title = task.Title,
//Specify the DateTimeKind to be UTC
Start = Convert.ToDateTime(task.Start),
End = Convert.ToDateTime(task.End),
Description = task.Deschription,
}).AsQueryable();
return Json(tasks.ToDataSourceResult(request));
}
}
I get an error on the DataSourceRequest: the type or namespace DataSourceRequest could not be found. But I can't find to narrow down which module I'm missing or what else I'm doing wrong...
Besides that I also get the following error System.LinqIQueryable doest not contain a definition for ToDataSourceResult. on the code:
return Json(tasks.ToDataSourceResult(request));
Anyone who can help me here or has an other/better solution to make a connection to a local database using the open source Kendo UI Scheduler?
Any help would be really appreciated!
You need to specify the allow get behavior.
return Json(tasks.ToDataSourceResult(request), JsonRequestBehavior.AllowGet));
I really looked, googled, this site, for a few days now, tried a bunch of different things, and I can't find an answer.
so, I'm trying to create a web application that will display client information after purchase. I'm using VS2012 express and C#, and I decided to use MVC4, mostly because there was a tutorial on ASP.NET that came pretty close to what I was looking to do. Any comments on my choices is not requested but also not unwelcome.
So the admin will enter all sales information at the end of each day. We record client phone numbers as account numbers in our sales protocol, so my thought was, to keep it simple, to just use the clients phone number as a login to the web application as well. Also, that way, when a client logs into the site to view the database, the database would filter automatically so that the particular client could only see their transactions.
The tutorial I followed is here.
I figured out that this is the point where the filter needs to be applied, but i'm having a lot of trouble doing so.
The controller is named "MainController"
The database is named "Main", table is "Mains"
"AccountNumber" is the field in the db that should match the Current User Id
public ActionResult Index()
{
return View(db.Mains.ToList());
}
As I understand it, I have to place [InitializeSimpleMembership] above, then grab the UserId, then define it as the filter.
First of all, you should decide one of these way:
1) keeping login and user info in a separate table and let the SimpleMembership(SM) does its default jobs.
2) Using an existing table so store users info and tell the SM which table is for.
Approach One:
To handle this approach, all you need is that you create users manually(as you do, I think) and add an extra line to the action method which is responsible of creating customers:
[HttpPost]
public ActionResult Create(Customer model)
{
if (ModelState.IsValid)
{
db.Customers.Add(model);
try
{
db.SaveChanges();
// here it is ...
WebSecurity.CreateUserAndAccount(model.Phone, model.Password);
}
catch
{
insertError = true;
}
// .. Other codes ...
}
Now, your customers can simply login to the site with their phone no. as username and that password.
And to retrieve items related to a specific user - which is currently logged into site - simply use the following query:
public ActionResult Index()
{
return View(db.Mains.Where(m => m.AccountNumber == User.Identity.Name)
.ToList());
}
If you also need approach two, tell me to update my answer and put it here
I have 8 pages labeled Step0-Step7 that are used to save data incrementally to a model called dr405. After Step7, I need to display an Upload.cshtml that creates a folder based on DR405Profile.CurrentUser.TangiblePRopertyID from my custom Profile provider. So, as of right now I'm not posting anything from from Step7 to the Upload.cshtml. After Upload.cshtml I display an UploadSummary.cshtml that simply list the files located in the directory based on DR405Profile.CurrentUser.TangiblePRopertyID. Now, I have to take the user to a review page that displays the DB persisted data for the dr405 model. Does this mean I have to pass my model through Upload and UploadSummary as well even though those pages don't interact with the model?
My plan is to pass the ID as a hidden parameter from
step7 -> Upload -> UploadSummary -> Review(id) <--post accepts ID as parameter. I'm not sure if this is the best way.
Important point
I want to understand if I can do the same with the model
Step7(model) --> Upload(model) -->UploadSummary(model) -->Review(id Or Model)
public ActionResult Review(string id)
{
var service = new DR405Service();
var dr405 = db.dr405s.FirstOrDefault(d => d.TangiblePropertyId == id);
return View(dr405);
}
public ActionResult UploadSummary()
{
var saveLocation = Path.Combine(Server.MapPath("\\"), "returns\\" + DR405Profile.CurrentUser.TangiblePropertyId);
ViewData["files"] = Directory.GetFiles(saveLocation).ToList() ;
return View();
}
[HttpPost]
public ActionResult Upload(HttpPostedFileBase uploadfile)
{
var saveLocation = Path.Combine(Server.MapPath("\\"), "returns\\" + DR405Profile.CurrentUser.TangiblePropertyId);
System.IO.Directory.CreateDirectory(saveLocation);
uploadfile.SaveAs(Path.Combine(saveLocation, Path.GetFileName(uploadfile.FileName)));
ViewData["UploadStatus"] = String.Format("File name: {0}, {1}Kb Uploaded Successfully.", uploadfile.FileName, (int)uploadfile.ContentLength / 1024);
return View();
}
You have a few options to persist the data across requests.
You can use the MVC TempData feature. You can use the Peek/Keep feature of TempData to keep it around until you need to dispose of it (as by default once the data is accessed it is deleted).
Session would also work, but isn't recommended due to it being harder to test in a unit test.
This is perfectly fine. Taking in the ID of a database entry is standard practice. It requires less bandwidth, allows MVC to resolve the correct route/controller/action faster, and doesn't give bad guys as much surface are for sending malicious data to your server.