ASP.NET MVC Passing ID from Controller to View - asp.net-mvc

Hi I am trying to pass an ID from the URL from a controller to a view. I am also passing a viewmodel that contains two models that have data from a database. Is there another way of doing this? The routemap has been set to send an ID.
The URL would be http://localhost:55147/Home/ViewProject/8 which obviously 8 is the ID of the project, but it does not seem to get this. I am passing the ID to the ViewProject controller function by URL.Action which has the ID passed through the parameter on another page.
Here is my controller:
public ActionResult ViewProject( int? id )
{
if( id == null )
{
return new HttpStatusCodeResult(HttpStatusCode.BadRequest);
}
BextecODBEntities DB = new BextecODBEntities();
var mymodel = new Multipledata();
mymodel.projectss = DB.Projects.ToList();
mymodel.projectnotess = DB.ProjectNotes.ToList();
return View("ViewProject", mymodel);
}
Here is my View:
#foreach(var item in Model.projectss)
{
if( item.ID.ToString() == Html.ViewContext.RouteData.Values["id"].ToString() )
{
#Html.DisplayText("You have clicked on Project ID:" + item.ID.ToString())
}
}
My multiple data model contains:
public IEnumerable<Projects> projectss { get; set; }
public IEnumerable<ProjectNotes> projectnotess { get; set; }

Instead of sending a list of Projects I have sent the specific Project data I have defined in the database model using the Project.Find(id) passed through the parameter like you have said

Related

Asp.net mvc call entity db data using Id for that particular row

Hi and thank you for taking your time to read. I am having trouble calling from a db using entity framework for a particular row. Here is my code for controller.
public ActionResult MyAccount(CurrentAccount ca, SaverAccount sa, int id)
{
var model = db.CurrentAccounts.FirstOrDefault(_ => _.Id == id);
Session["Id"] = ca.Id;
Session["CurrentAccountNumber"] = ca.CurrentAccountNumber;
Session["CurrentBalance"] = ca.CurrentBalance;
Session["SaverAccountNumber"] = sa.SaverAccountNumber;
Session["CurrentBalance"] = sa.SaverAccountNumber;
return View(model);
}
My model is a edmx entity file and i can seem to retrieve some data to my locals but only from 1 table and i need data to be from multiple tables selecting a full row of data for a paricular Id then having this information visable on the same view. There is also a relation between id on both tables. Thanks :)
Here you have called wrong object because you are fetching data in model variable but calling from ca. please use as following
public ActionResult MyAccount(CurrentAccount ca, SaverAccount sa, int id)
{
var model = db.CurrentAccounts.FirstOrDefault(_ => _.Id == id);
Session["Id"] = model.Id;
Session["CurrentAccountNumber"] = model.CurrentAccountNumber;
Session["CurrentBalance"] = model.CurrentBalance;
Session["SaverAccountNumber"] = sa.SaverAccountNumber;
Session["CurrentBalance"] = sa.SaverAccountNumber;
return View(model);
}
You need to execute join query to get data from two models like following exmaple
Create a common class like follwing
public class datafrombothclass
{
public int Id { get; set; }
public String saveaccount_name { get; set; }
public String currrentaccount_name { get; set; }
}
Now use join query in entity framework to get data from both model in you case from CurrentAccount and SaverAccount.
See the bellow code example:
var frombothclass=(from a in Model.saveaccount join s in Model.currentaccountaccount
where a.Id=id
select new datafrombothclass{
Id=a.Id,
saveaccount_name=s.name,
currrentaccount_name=a.name
});
return View(frombothclass);
Hope you will get the solution.

Pass parameter value from url back to view module

I am trying to pass a parameter value from my url back to the view model. Here is the url: StudentDetails/MarkingToolView/1?studentId=1
I am trying to get the first parameter of 1 (after MarkingToolview/) so I can post it back to my database
my viewModel:
public class MarkingVM
{
public int? ModuleID { get; set; }
}
my view:
#Html.HiddenFor(m => m.ModuleID, new { id = ??? })
What is the best way to do this?
I think you are asking how to get the url parameter into your view perhaps? Something like the following will populate your view model.
Controller
public action MarkingToolView(int studentId)
{
MarkingVM vm = new MarkingVM(); //or however that is initialized.
vm.ModuleID = studentId;
return View(vm);
}

MVC Viewmodel cant access model with View

How can I access my viewmodel from my view? my code is as follows:-,
I have two models (using entity framework) which have a view model of:-
public class ViewModelStory
{
public IEnumerable<tbl_GCB_NewsItem> GCB_NewsItem { get; set; }
public IEnumerable<tbl_GCB_ItemComment> comemnts { get; set; }
}
My contoller populates the models by:-
ViewModelStory.GCB_NewsItem = (from i in db.tbl_GCB_NewsItem
where i.intItemIdentifier.ToString() == StoryId
select i).SingleOrDefault();
ViewModelStory.comemnts = (from i in db.tbl_GCB_ItemComment
where i.intItemIdentifier.ToString() == StoryId
select i).ToList<tbl_GCB_ItemComment>();
I return the model by
return PartialView("NewsStory", ViewModelStory);
then in my view I have the following declaration
#model ViewModelStory
#using GCBSMVC.Models
To access my model I have tried various from Linq to and directly querying the model, but nothing seems to work:-
Html.DisplayFor(m =>m.GCB_NewsItem. ....
ViewModelStory.GCB_NewsItem.strItemCategory
Html.Raw(System.Web.HttpUtility.HtmlDecode(ViewModelStory.GCB_NewsItem.strItemHeadline))
You are passing the type of you model class instead of the actual class. Try this:
var model = new ViewModelStory();
model.GCB_NewsItem = (from i in db.tbl_GCB_NewsItem
where i.intItemIdentifier.ToString() == StoryId
select i).SingleOrDefault();
model.comemnts = (from i in db.tbl_GCB_ItemComment
where i.intItemIdentifier.ToString() == StoryId
select i).ToList<tbl_GCB_ItemComment>();
return PartialView("NewsStory", model);

MVC pass viewmodel view with viewmodel containing parent values and child list

My application has multiple areas within one facility. I am trying to pass a single model to the view that contains facility values (facility_id, facility_name), and a list of areas. I currently have the list of areas as a type of the entity model for the table (area_list).
My viewmodel is as follows:
public class AreaView
{
public string facility_name { get; set; }
public int facility_id { get; set; }
public int group_id { get; set; }
public IList<area_list> areas { get; set; }
}
As an aside, I had originally tried setup the list of areas as a separate viewmodel (AreaS) instead of the model area_list, but I had other issues there so went back to directly referencing the for simplicity. I am assuming this would be more appropriate...
My Controller:
public ActionResult List(int id = 0)
{
var model = (from f in areaDB.facility_list
where f.facility_id == id
select new AreaView
{
facility_id = f.facility_id,
facility_name = f.facility_name,
areas = (from a in areaDB.area_list
orderby a.area_name
where a.facility_id == id
select a).ToList()
});
return View(model);
}
My View (abbreviated):
#model SkyeEnergy.Models.AreaView
Facility: #Model.facility_name
#foreach (var item in Model.areas) {
<tr>
<td>
#Html.ActionLink(item.vendor_name,"Details","Area",new {id = item.vendor_id},null)
</td>
</tr>
}
I have tried numerous variations to accomplish what's below, which has given me numerous errors, but the most recent is below:
The model item passed into the dictionary is of type
'System.Data.Entity.Infrastructure.DbQuery`1[MyApp.Models.AreaView]',
but this dictionary requires a model item of type
'MyApp.Models.AreaView'.
I understand that I am not passing the correct type for what the view is expecting, but I cannot seem to figure out:
Is the viewmodel setup correctly in the firstplace (how to mix values and a list of children
How to structure my linq query to get one AreaView object with
all my data
Pass it appropriately (in the correct type) to my
view
I have read about 45 posts on Stackoverflow, but can't seem to piece them together to accomplish what's above. If anyone has a correct solution (or even a direction), I would be very appreciative.
Thanks for any help.
I think you should add FirstOrDefault() at the end of your query to return the AreaView
public ActionResult List(int id = 0)
{
var model = (from f in areaDB.facility_list
where f.facility_id == id
select new AreaView
{
facility_id = f.facility_id,
facility_name = f.facility_name,
areas = (from a in areaDB.area_list
orderby a.area_name
where a.facility_id == id
select a).ToList()
}).FirstOrDefault();
return View(model);
}
I would not combine both object in the same query. I would do
1) Select AreaView where id = xxxx
2) Select Areas where id = xxxx
3) Assign areas to my AreaView
Example
AreaView model = GetAreaView(id);
model.Areas = GetAreas(id);
return View(model);
Also, try the following for your current code
return View(model.FirstOrDefault());

Accessing group by fields from Controller to View in MVC 3

How can I write code in View so as to access the groupby fields in linq. Here the data is rendered through a web service.
public class HomeController : Controller
{
public ActionResult Index()
{
ViewBag.Message = "Find Member";
var obj = new SearchMemberServiceClient();
List<MemberProxy> members = obj.FindMember("Mason", "Birkes", "", "", "", "").Members;
var sorted = from a in members
orderby a.FirstName ascending
group a by new { a.FormattedFullName, a.PersonId, a.Associations, a.MembershipsProxy[0].MembershipId } into k
select new { formattedname = k.Key.FormattedFullName, id = k.Key.PersonId, assoc = k.Key.Associations, memprox = k.Key.MembershipId };
return View(sorted.ToList());
}
}
You are passing an anonymous object to your view. Anonymous objects are emitted as internal by the compiler. Internal classes can only be used within the same assembly. ASP.NET MVC views are dynamically compiled by the ASP.NET runtime in separate assemblies. This basically means that you cannot access the anonymous types created in your controller actions inside your views. As a consequence this means that you should absolutely never pass anonymous objects to your views. So if you cannot pass anonymous objects, well, pass a named object by creating one. In this case they will be called a view model. A view model is class that you specifically define to meet the requirements of your view.
So what are the requirements of your view is the first question you should ask yourself when designing an ASP.NET MVC application? Well, in this case you seem to need a couple of properties (formattedname, id, assoc and memprox). Great, let's write a view model:
// you probably want to find a more suitable name
public class MyViewModel
{
public int Id { get; set; }
public int MemProx { get; set; }
public string FormattedName { get; set; }
public IEnumerable<Association> Associations { get; set; }
}
and then have your action pass this view model to the view:
public ActionResult Index()
{
var obj = new SearchMemberServiceClient();
var members = obj.FindMember("Mason", "Birkes", "", "", "", "").Members;
IEnumerable<MyViewModel> sorted =
from a in members
orderby a.FirstName ascending
group a by new
{
a.FormattedFullName,
a.PersonId,
a.Associations,
a.MembershipsProxy[0].MembershipId
} into k
select new MyViewModel
{
FormattedName = k.Key.FormattedFullName,
Id = k.Key.PersonId,
Associations = k.Key.Associations,
MemProx = k.Key.MembershipId
};
return View(sorted.ToList());
}
OK, now you can strongly type your view to this view model and present the information that it contains however you want:
#model IEnumerable<MyViewModel>
#foreach (var item in Model)
{
<div>#item.FormattedName</div>
...
}

Resources