mvc 3 return view with other objects - asp.net-mvc-3

I have a details page that returns a profile view that is basically used to find the page number from the database. I also have a separate query that I would like to return in the return view but cannot figure out how to. The code I have is
public ActionResult detail(int id)
{
profile profile = db.profiles.Find(id);
var currentpage = (from s in db.profiles where id == s.profileID select s.registrationID).FirstOrDefault();
var articles = (from s in db.Articles where currentpage == s.RegistrationID select s.title).FirstOrDefault();
ViewBag.articles = articles;
ViewBag.noprofiler = " This profile currently doesn't have the email profiler selected";
return View(profile);
}
i would like to also return articles i put it into a viewbag but that is not working any ideas ?

If articles is populated then you should be able to access it in the view via ViewBag.articles
Maybe you should check what is in the articles variable here in the controller function.
Also the variable name articles suggests you're looking for a list but you are using FirstOrDefault() which would return a single object (or null).

Related

How to show custom query result to view mvc3 Razor

I have Custom query Result as
public ActionResult Index()
{
var Query = (from E in db.SITE_MASTER.AsEnumerable()
where E.IS_PAGE == true
select new
{
E.POST_TITLE,
E.POST_TEXT
}).ToList();
return View(Query);
}
Now,
How can I make view for this result or How can I create View for this Result Query.
Thanks...
You can pass an anonymous type as a model, but please don't. It's ugly and will lead to maintenance problems.
As an alternative either use the ViewBag or create concrete type and pass that.

Set passed value in my ActionResult

I have two independent classes that model my tables. First when a new user is created, the user does not have a record in the certificate tables. So in the view for the certificates I have added a button to add certificates details for this new user.
This is my code for the user view: I omitted the paging/search and filter code to make it simple
public ActionResult Index()
var recipients = from s in db.User
select s;
return View(recipients.ToList());
This is the details view showing related data:
public ViewResult Details(int id)
{
var certificateDetails = db.Certificate.Where(p => p.ID == id);
return View(certificateDetails);
}
Adding a new user means also adding a new certificates details. I want when a user clicks details for the a particular user if those details aint around to be redirected to a create certificate view with both User.ID and CertificateID set. In fact CertificateID is AI but ID from User is foreign key.
I would have used Fluent API but am not good with it either so have to handle this seemingly small challenge in code.
If I understand your question correctly, you want it so that when you view Details(), if the certificate details don't exist, then redirect to a page to create them?
Just check whether or not the entity exists. If it doesn't, return a RedirectToAction() and pass whatever data you need in the route data collection.
public ViewResult Details(int id)
{
var certificateDetails = db.Certificate.FirstOrDefault(p => p.ID == id);
if (certificateDetails == null)
return RedirectToAction("Create", "Certificate", new { userId = id });
return View(certificateDetails);
}
You'll also need to create a Certificate controller with a Create() action.

How to pass value from one action to another action having different views in mvc3

Hi I am developing an application in MVC3.
and i am stuck at one place.
I have 2 fields in my view which are not a part of my class.
i am just using them to populate the dropdown
The 2 fields are State and District.
But i want to show the selected value of the two fields in another View.
I tried it using ViewBag but this doesnot work and gives me Null.
this is inside Create get method:
int stateid = Convert.ToInt32(formcollection["ProvincialState.ProvincialStateID"]);
int districtid = Convert.ToInt32(formcollection["District.DistrictID"]);
ProvincialState state = new AddressService().FetchStateByStateId(stateid);
District district = new AddressService().FetchDistrictByDistrictId(districtid);
ViewBag.State = state.ProvincialStateName;
ViewBag.District = district.DistrictName;
and this is inside Details View:
string data1 = ViewBag.State;
string data2 = ViewBag.District;
ViewBag.State = data1;
ViewBag.District = data2;
I cannot use post method of Create coz i need to show this data only on another view.
or if is their any method thru which i can show the data in the same view.
ViewBag is like ViewData. In order to have information between pages you should store that info in session. You can do that in 2 ways:
Use a session variable like:
this.Session["SessionVariable"] = value;
Or use the this.TempData object:
this.TempData["SessionVariable"] = value;
The difference between this two is that the TempData object will be deleted from the session when it is read.
TempData is just a wrapper of the session.
You can send this fields to your action in addition to model, and then store it in session for example:
public class SomeController: Controller
{
[HttpPost]
public ActionResult DoSomething(MyModel model, int state, int district)
{
// validating model...
// ...
Session["state"] = state;
Session["district"] = district;
// some other logic...
}
}

Displaying records from database which are equal to logged on user

I have created an MVC3 application which needs to show user specific data. The problem I am having is trying to display records which are equal to #user.Identity.Name.
The following Linq to SQL has been used to try to accomplish this:
public ActionResult Index()
{
using (var db = new mydatEntities())
{
var details = from t in db.testadtas
where t.UserID == Viewbag.UsersRecord
select t;
return View();
}
}
(Update)
New to c# and Linq and finding it hard to write a query which will only display the logged on users records.
I have used the code below
MembershipUser currentUser = Membership.GetUser (User.Identity.Name, true /* userIsOnline */);
Viewbag.UsersRecord = currentUser.ProviderUserKey;
I have then input the Viewbag.UserRecord into a textbox which updates a database field with the UserID in a table I have created.
I now want to write a linq query to say if UserID = Viewbag.UserRecord then show record with the UserID only
Is this a correct method to use for showing logged on user records?
or is there any other way which I can implement this in MVC3?
Just use HttpContext.User.Identity.Name

MVC 3 Details View

I am new to MVC frame work. And i am making one page where we can see details of department by clicking on details link button.
While User click link button it fetch the all the records of the particular department in List Collection and redirect to Details View.Data has been fetched in List but while going to Details view it Generates following error:
The model item passed into the dictionary is of type 'System.Collections.Generic.List1[DocPageSys.Models.Interfaces.DepartmentInfo]', but this dictionary requires a model item of type 'DocPageSys.Models.Interfaces.DepartmentInfo`'.
I understood the error but confusion to solve it.And stuck with this problem...
Since your Details view is strongly typed to DepartmentInfo:
#model DocPageSys.Models.Interfaces.DepartmentInfo
you need to pass a single instance of it from the controller action instead of a list:
public ActionResult Details(int id)
{
DepartmentInfo depInfo = db.Departments.FirstOrDefault(x => x.Id == id);
return View(depInfo);
}
So make sure that when you are calling the return View() method from your controller action you are passing a single DepartmentInfo instance that you have fetched from your data store.
To make it run fine initially you could simply hardcode some value in it:
public ActionResult Details(int id)
{
var depInfo = new DepartmentInfo
{
Id = 1,
Name = "Sales",
Manager = "John Smith"
}
return View(depInfo);
}
Oh, and you will notice that I didn't use any ViewData/ViewBag. You don't need it. Due to their weakly typed nature it makes things look really ugly. I would recommend you to always use view models.
Passing a list instead of a single item
This error tells you, that you're passing a list to your view but should be passing a single entity object instance.
If you did fetch a single item but is in a list you can easily just do:
return View(result[0]);
or a more robust code:
if (result != null && result.Count == 1)
{
return View(result[0]);
}
return RedirectToAction("Error", "Home");
This error will typically occur when there is a mismatch between the data that the controller action passes to the view and the type of data the view is expecting.
In this instance it looks as if you're passing a list of DepartmentInfo items when your view is expecting a single item.

Resources