Filtering in MVC - sql

Im new to MVC. How can i filter and get all the records displayed related to a particular dataitem. Eg. If i click to Id =2 i want to display all items which has id=2. Please could anyone help

In your controller, you want to use LINQ. For example:
public ActionResult GetListOfSomething()
{
var context = new MyDataContext();
var model= new MyModel();
model.ItemList = context.MyObject.Where(x => x.SomeProperty == "SomeValue").ToList();
return View(model);
}
This is a pretty simple example, but illustrates the concepts.

Related

Data is not inserting to the database

I am new to asp .net MVC 4.
I have one text box and the text box value I am fetching from one table.But while clicking on submit button this value I want to insert into different table , which is not inserting and showing error.It is taking value as null.
coding
View
#Html.TextBox("empname", (string)ViewBag.empname, new { #readonly = "readonly" })
controller
[HttpGet]
public ActionResult Facilities()
{
mstEmpDetail emp = new mstEmpDetail();
emp = db.mstEmpDetails.Single(x => x.intEmpId == 10001);
ViewBag.empname = emp.txtEmpFirstName;
return View();
}
[HttpPost]
public ActionResult Facilities(TrnBusinessCardDetail bc)
{
var empname1 = ViewBag.empname;
bc.txtfirstName = empname1;
db.TrnBusinessCardDetails.Add(bc);
db.SaveChanges();
return RedirectToAction("Facilities");
}
While I was working with normal text box it was inserting properly,but when I have retrieve
fro DB then i am getting this problem ?
How to solve this problem ?
Viewbag is a one way street - you can use it to pass information to the view, but you cannot use it to get the information from the view. The statement ViewBag.empname in your POST method has a value of null in your code.
As suggested by #dotnetom, ViewBag is a one way street. MVC is stateless so a POST request is not a "Round Trip" from previous get request. Thus your ViewBag can not hold its state.
MVC can determine (and construct) your action parameters from Form Parameters. In your case you have added a textbox with name "empname". So you should get this value as parameter in your POST request.
[HttpPost]
public ActionResult Facilities(TrnBusinessCardDetail bc, string empname)
{
bc.txtfirstName = empname;
db.TrnBusinessCardDetails.Add(bc);
db.SaveChanges();
return RedirectToAction("Facilities");
}
This would be simplest of solution given your problem. More appropriate would be binding your textbox directly with you model property. This way you will not have to worry about retrieving and assigning property value to model in your controller.
I think the problem is when you are using var empname1 = ViewBag.empname; in post controller because ViewBag.empname lost its value at that time.

how do i create a dynamic view for data entry

What i want in the view is to spit out the fields that are part of the Department and Employee models depending on whichever one gets mentioned in the URL.
say for example department model has 5 fields
How do i create a view (dynamic/not strongly typed) that automatically displays the fields based on the model and let the user enter the values?
[HttpGet]
public ActionResult Create(string process)
{
if (process.Equals("Department"))
{
var model = new Department();
return View(model);
}
else if (process.Equals("Employee"))
{
var model = new Employee();
return View(model);
}
else
return View();
}
You can pass it as an object. You could also pass it in the viewdata (or viewbag). For both of these ways you would also need to include a flag so you know which one you should cast to. Both of these ways in my opinion though are hokey and prone to problems.
Another way would be to create a view model that combines both models. I personally would try to keep them separate and use separate calls \ views for each, depending on the requirements.

The model item passed into the dictionary is of type 'System.Collections.Generic.List`1[X]', but this dictionary requires a model item of type 'X'

*CORRECTION
The problem occurs when my view is called to populate a list from my user table.
The model item passed into the dictionary is of type 'System.Collections.Generic.List`1[Mike.Models.User]', but this dictionary requires a model item of type 'Mike.Models.User'.
Here is my controller action:
public ActionResult Registration(Mike.Models.User user)
{
if (ModelState.IsValid)
{
using (var db = new UserContext())
{
var crypto = new SimpleCrypto.PBKDF2();
var encrypPass = crypto.Compute(user.password);
var sysUser = db.Users.Create();
sysUser.LastName = user.LastName;
sysUser.FirstName = user.FirstName;
sysUser.Email = user.Email;
sysUser.password = encrypPass;
sysUser.passwordSalt = crypto.Salt;
sysUser.UserID = user.UserID;
db.Users.Add(sysUser);
db.SaveChanges();
return RedirectToAction("Index", "Home");
}
}
return View(user);
}
Can someone please help me.... There are responses to similar questions on the internet but I believe mine is unique.. I have searched for weeks to no avail.
Thanks in advance,
Renior
Here is my simple controller action...
public ActionResult Index()
{
return View(db.Users.ToList());
}
and my razor syntax.
#model IEnumerable
Im trying to populate a view of my user table list..
In your Registration view at the top where your model declaration is, instead of this:
#model List<Mike.Models.User>
you need to have:
#model Mike.Models.User
You probably used strongly typed scaffolding feature to generate your view but instead of details option you chose a list option...
Take this at face value - yours is not unique. Your problem is you are passing an array of user to a controller action that expects a user.
You need to post your HTML but it is probably something like #model List user or something instead of a single user.
If your model represents a single user then pass that to the controller. If opposite, do opposite,
If you want to pass a list to the controller use list users
edit
make your razor syntax
#model Mike.Models.User

MVC 4 Partial with separate Controller and View

I've developed ASP.NET Forms for some time and now am trying to learn MVC but it's not making total sense how to get it to do what I want. Perhaps I need to think about things differently. Here is what I'm trying to do with a made up example:
Goal - Use a partial file, which can be placed anywhere on the site which will accept a parameter. That parameter will be used to go to the database and pass back the resulting model to the view. The view will then display one or more of the models properties.
This isn't my code, but shows what I'm trying to do.
File: Controllers/UserController.cs
[ChildActionOnly]
public ActionResult DisplayUserName(string userId)
{
MyDataContext db = new MyDataContext()
var user = (from u in db.Users where u.UserId = userId select u).FirstOrDefault();
return PartialView(user);
}
File: Views/Shared/_DisplayUserName.cs
#model DataLibrary.Models.User
<h2>Your username is: #Model.UserName</h2>
File: Views/About/Index.cshtml
#{
ViewBag.Title = "About";
}
<h2>About</h2>
{Insert Statement Here}
I know at this point I need to render a partial called DisplayUserName, but how does it know which view to use and how do I pass my userId to the partial?
It's what I expect is a very basic question, but I'm yet to find a tutorial which covers this.
Thanks in advance for your help.
You should call Html.Action or Html.RenderAction like:
#Html.Action("DisplayUserName", "User", new {userId = "pass_user_id_from_somewhere"});
Your action should be like:
[ChildActionOnly]
public ActionResult DisplayUserName(string userId)
{
MyDataContext db = new MyDataContext()
var user = (from u in db.Users where u.UserId = userId select u).FirstOrDefault();
return PartialView("_DisplayUserName", user);
}
This should do the trick.
I always make sure to close the MyDataContext... Maybe enclose everything in a using statement... If you notice when VS does it for you they create the entity as a private variable in the Controller Class (outside of the controllers) and then close it with the dispose method... Either way I believe you need to make sure those resources are released to keep things running smooth. I know it's not in the question but I saw that it looked vulnerable.

How to Create ViewModel with multiple related tables and Save Form

I am trying to figure out the best way to accomplish this given the modern versions. I have am using VS2012 MVC4 EF5 and have built a edmx file from my database. I built a form that will allow submission of vendor information. The main table is Vendor table that contains mainly contact information and there are additional tables that store their multiple category choices (checkbox list) and another that stores their minority info (collection of radio buttons). So my ViewModel is the vendor table and I populate the checkboxes and radio buttons with view bags that query the lookup tables for their values.
So I assume I should either build the categories and minority parts into the ViewModel and somehow wire up the magic so that the database knows how to save the returned values or should I just use viewbags and then somehow on post read those values and loop through them to store them to the database? Either way I am stuck and don't know how to do this.
I have serached numerous examples online but none of them fit this situation. The is not a complex data model but should be rather common real world situation. I am new to MVC so forgive me if I am missing something obvious.
Any guidance is appreciated.
UPDATE: Here is the baseic code to save the ViewModel to the db but how do you save the checkbox list and radio buttons. I think there are two approaches 1) to somehow include them in the ViewModel or 2) perform a separate function to save the form checkbox and radio button values.
[HttpPost]
public ActionResult Form(VendorProfile newProfile)
{
if (ModelState.IsValid)
{
newProfile.ProfileID = Guid.NewGuid();
newProfile.DateCreated = DateTime.Now;
_db.VendorProfiles.Add(newProfile);
_db.SaveChanges();
return RedirectToAction("ThankYou", "Home");
}
else
{
PopuplateViewBags();
return View(newProfile);
}
}
Perhaps another way of stating my problem is what if you had to build an form to where people would sign up and select all their favorite flavors of ice cream from a list of 31 flavors. You need to save the person's contact information in the primary table and then save a collection of their flavor choices in another table (one-to-many). I have a ViewModel for the contact form and a list of flavors (checkbox list) displayed from a lookup table. How do you write code to save this form?
SOLUTION: There might be a better way, but wanted to post what I discovered. You can pass in the collection of checkboxes and then send them to another method that handles the db inserts.
[HttpPost]
public ActionResult Form(VendorProfile newProfile, int[] categories)
{
if (ModelState.IsValid)
{
newProfile.ProfileID = Guid.NewGuid();
newProfile.DateCreated = DateTime.Now;
_db.VendorProfiles.Add(newProfile);
_db.SaveChanges();
InsertVendorCategories(newProfile.ProfileID, categories);
return RedirectToAction("ThankYou", "Home");
}
else
{
PopuplateViewBags();
return View(newProfile);
}
}
private void InsertVendorCategories(Guid ProfileID, int[] categories)
{
try
{
var PID = new SqlParameter("#ProfileID", ProfileID);
var CID = new SqlParameter("#CatID", "");
foreach (int c in categories)
{
CID = new SqlParameter("#CatID", c);
_db.Database.ExecuteSqlCommand("Exec InsertVendorCategory #ProfileID, #CatID", PID, CID);
}
}
catch { Exception ex; }
}