retrieve values from model in mvc2 - asp.net-mvc-2

I don't know how to create functions to retrieve the values.
*Table 1: OrgVasplans*
-Id
-vasplanId
-OrgId
-CreatedDate
Table-2: vasplans
-Id
-name
-amount
-validity
-vasdurationId
Table-3: VasDuration
Id
Duration.
These are my tables..
I have Controller named Candidatesvas and action method VasDetails....
I already stored the values into vasPlans table.
when I click in view "Details" link it will go to details page..
Then the values are retrieve from "Orgvasplans" table automatically without enter any input..
How to create methods for this....
I created some methods but the method contains only Name "field". I want to retrieve multiple values like "Amount", "validity" like that.....
Repository:
public IQueryable<VasPlan> GetVasPlans()
{
return from vasplan in _db.VasPlans
orderby vasplan.Name ascending
select vasplan;
}
public OrgVasPlan GetOrgVasPlan(int id)
{
return _db.OrgVasPlans.SingleOrDefault(v => v.Id == id);
}
public int AddOrgVasPlan(OrgVasPlan orgvasplan)
{
_db.OrgVasPlans.AddObject(orgvasplan);
Save();
return orgvasplan.Id;
}
public void AddVasPlan(VasPlan vasPlan)
{
_db.VasPlans.AddObject(vasPlan);
}
Controller
public ActionResult VasDetails(FormCollection collection)
{
OrgVasPlan orgvasplan = new OrgVasPlan();
orgvasplan.CreatedDate = DateTime.Now;
orgvasplan.OrgId = LoggedInOrganization.Id;
orgvasplan.vasplanId=??????????????
VasPlan vasplan = new VasPlan();
//if (!string.IsNullOrEmpty(collection["Name"])) ;
_repository.AddOrgVasPlan(orgvasplan);
_repository.Save();
return View();
}
Here i don't know how to put code here for get multiple values form vasplans table like(amount,name,validity etc...,)
this is my problem...

Make your view strongly-typed, make sure you create input elements whose names correspond to the model properties (or use HTML helpers, e.g. Html.TextBoxFor(model => model.Amount). That way MVC will automatically fill in the model for you when the action that should take the model as a argument, is invoked.
For example your action should be:
public ActionResult NewVasPlan(VasPlan vplan)
{
//check model state
//save or return error messages
}
Or you can simply add string and int parameters to the Action like this:
public ActionResult NewVasPlan(string name, int amount /*, etc*/)
{
//MVC will also automatically fill name, amount, from request POST or GET params
//(or cookies??)
}
Hope this helps, tell me if you need more info or if I misunderstood your question.

Related

EF Core - many-to-many: how to add middle entity when one entity does not yet exist?

I am curios if I can make this easier/better.
The user is able to create new tickets and with each ticket can be several files associated, one file can be related to multiple tickets.
Now, when the user creates a ticket, he can already add files. Meaning I have no Id for the ticket and thus no way to build a relation. How should I solve this?
public class FilesPerTicket
{
public int TickedId;
public Ticket Ticket;
public int FileId;
public File File;
}
public class File
{
public ICollection<FilesPerTicket> FilesperTicket;
}
public class Ticket
{
public ICollection<FilesPerTicket> FilesperTicket;
}
Now the user creates the ticket and adds several files to it.
public IActionResult Create(MyModel model)
{
// .....
var filesPerTicket = model.Files.Select(x => new FilesPerTicket() { FileId = x.Value }).ToList();
var newTicket = new Ticket() { //...... };
newTicket.FilesPerTicket = filesPerTicket;
// ....
context.Add(newTicket);
context.SaveChanges();
}
This doesn't work because we haven't provided a Ticketid and therefore every TicketId in FilesPerTicket is 0.
I know that I just can save the ticket and afterwards it will have the primary key in it. Which I then can use to fill the FilesPerTicket and save that one.
But then I would have those in separate transactions (because SaveChanges was called) and use another try/catch.
Is there an way to tell EF Core to fill this TicketId automatically when this entity gets saved at the same time as a ticket? Or some other way to save that entity?

WebApi create and EF Inheritance

I have following entities:
abstract class User
{
string Id
string Name
}
class UserA: User
{
string PropA
}
class UserB : User
{
string PropB
}
It is a good solution to have a unique create (post) with a dynamic parameter and instantiate the subclasses according to a property?
[HttpPost]
public IActionResult Create([FromBody]dynamic data)
{
if (data.PROP == null)
{
_context.Users.Add(new UserA(data.PropA));
}
else
{
_context.Users.Add(new UserB(data.PropB));
}
...
Don't use dynamic. I'm actually kind of surprised that works at all. Though there's no indication that you've actually tested this code yet, so perhaps it doesn't. The modelbinder needs to know a concrete type to bind to, so that it can determine how to map the values onto the destination instance. Without strong types, it can't do anything but make everything a string, since that is how it comes in the request body.
Anyways, for something like this, the correct approach is to use a view model. Your view model should contain all the properties for all the various possible derived types. Again, the modelbinder needs these to determine how to map the data from the request body over, so if a property doesn't exist, it will simply discard the associated data.
This is also why you cannot simply use the base class. If this were a normal method, you could do something like:
public IActionResult Create([FromBody]User data)
Then, inside, you could use pattern matching or similar to cast to the correct derived type. This works because ultimately, the object in memory would actually be an instance of something like UserA, and you're simply up-casting it to User. As a result, you can always cast it back to UserA. However, actions are different. What's coming in from the request is not an object instance. The modelbinder serves to create an object instance out of it, by inspecting the parameter it needs to bind to. If that parameter is of type User, then it will fill the properties on User, and discard everything else. As a result, the object in memory is just User, and there's no way to cast to something like UserA - at least in terms of having all the values that were actually posted for an instance of UserA being on the object.
Which brings us back to the view model:
public class UserViewModel
{
public string Id { get; set; }
public string Name { get; set; }
public string PropA { get; set; }
public string PropB { get; set; }
}
Then, have your action accept that as a param:
public IActionResult Create([FromBody]UserViewModel data)
Then, inside:
if (!string.IsNullOrWhiteSpace(data.PropA))
{
// UserA was posted, map data to an instance of UserA
}
Similarly for UserB. If you like, you could also post an explicit "type" along with the data and switch on that to instantiate the right type. It's up to you. To reduce code duplication, you can instantiate the right type, but store it in an variable of type User. Then, if you need to get back at the correct type, you can use pattern matching:
User user;
switch (data.Type)
{
case "UserA":
user = new UserA
{
Id = data.Id,
Name = data.Name,
PropA = data.PropA
};
break;
// etc.
default:
user = new User
{
Id = data.Id,
Name = data.Name
};
break;
}
Then later:
switch (user)
{
case UserA userA:
// do something specific with `userA`
// etc.
}
Or:
if (user is UserA userA)
{
// do something with `userA`
}

How to save the selected value from dropdownlist to database using Entity Framework in ASP.NET MVC 4

In my one of the view I add a dropdown and I bind this drop down with my database like this..
public ActionResult PostMarks()
{
JoinMod std = new JoinMod();
std.Drp_bind = (from nm in db.TbStudent
select new SelectListItem
{
Text = nm.StudentName,
Value = SqlFunctions.StringConvert((double)nm.StudentId).Trim()
}).ToList<SelectListItem>();
return View(std);
}
Here is the dropdownlist in my view
<p>StudentName</p>
#Html.DropDownList("StudentName",Model.Drp_bind,"Select")
And on Post I am trying to save the data into the database like this
[HttpPost]
public ActionResult PostMarks(Marks marks)
{
db.TbMarks.Add(marks);
db.SaveChanges();
return RedirectToAction("ShowAllMarks");
}
Now when I check my database after save data in database the Id save in the database is zero from the dropdownlist. Please experts help me to solve this issue
You should be using #HTML.DropDownListFor, specifying a lambda that indicates which property in your model you want to bind the list's selected value to on the POST.
Given a view model like so:
public class MarksViewModel
{
public Marks Marks { get; set; }
public IEnumerable<SelectListItem> Drp_bind { get; set; }
}
The drop down list in the CSHTML can be declared like so:
#Html.DropDownListFor(m => m.Marks.StudentId, m.Drp_bind, "Select a Student")
The first argument is an expression describing the property on your model that you want to populate with the selected value from the drop down list in the post back. The second is the list comprising the values to which we need to data bind.
Note that your CSHTML will need more form fields within it bound to the other properties of the Marks property.
Your POST method would now take MarksViewModel as an argument and extract the Marks property from it to add to the DbContext for saving.

Filter view data based on user input

This is my first MVC app and I'm not sure how to use a parameter to filter the returned data. I'm using MVC2 and Visual Studio 2008.
How do I filter view results based on user input? I want the user to be able to enter an ID number in a textbox and then click a button to get results filtered by the ID they entered.
here is my Controller
public class HelloWorldController : Controller
{
UAStagingEntities db = new UAStagingEntities();
public ActionResult Index()
{
var depot = from m in db.CSLA_DEPOT
where m.DEPOT_ID==10057
select m;
return View(depot.ToList());
}
}
how do I change this to accept a paramter instead of a hard coded ID?
Initially try getting it working from the address bar in your browser.
Change the code to receive an Id parameter:
public ActionResult Index(int Id)
{
var depot = from m in db.CSLA_DEPOT
where m.DEPOT_ID==id
select m;
return View(depot.ToList());
}
Then you should be able to call .../controller/action/id
Next add an actionLink to your webpage to call this action

Using ListBoxFor in ASP.NET MVC 2

I am trying to update the Roles a specific group has in my application. The Group model I use in my view has an additional AllRoles IEnumerable attached to it, so that in my view I can do something like this:
<%: Html.ListBoxFor( model => model.aspnet_Roles, new MultiSelectList( Model.AllRoles, "RoleId", "RoleName" ), new { #class = "multiselect" } )%>
This generates a multiple select drop down as expected. However, coming form PHP, I noticed that the name of the select was without square brackets, maybe that is OK in ASP.NET but in PHP it is wrong.
Now, how do I go about updating the group after submiting the form, more precisely, how can I read the multiselct selected values. What I need is that based on the RoleIds that I receive to Add respective aspnet_Roles to my Group model.
Trying to read the received values using HttpContext.Request.Form["aspnet_Roles"] failed and is also ugly. Can I somehow use the model to fetch the needed data? Controller function:
[AcceptVerbs( HttpVerbs.Post )]
public ActionResult Edit( SYSGroups updatedGroup ) {}
Thanks
The selected ids will be sent as a collection:
[HttpPost]
public ActionResult Edit(string[] aspnet_Roles)
{
// the aspnet_Roles array will contain the ids of the selected elements
return View();
}
If the form contains other elements that need to be posted you could update your model:
public class SYSGroups
{
public string[] Aspnet_Roles { get; set; }
... some other properties
}
and have your action method look like this:
[HttpPost]
public ActionResult Edit(SYSGroups updatedGroup)
{
// updatedGroup.Aspnet_Roles will contain an array of all the RoleIds
// selected in the multiselect list.
return View();
}