Is it possible to pass object as route value in mvc 3? - asp.net-mvc-3

I'm trying to refactor some of my code and i'm wondering if it is possible something like this:
This is part of my cshtml:
<a href="#Url.Action("Vote", "Ideas", new { id = item.Idea.Id, pageMetadata = Model.PageMetadata, numberOfVotes = 2 })">
This is invoking action:
public ActionResult Vote(string id,PageMetadata pageMetadata, int numberOfVotes = 1)
And PageMetadata is my class.
When im debbuging in cshtml site pageMetadata is correct,but when action is invoking pageMetadata it's becoming to null. Do I some stupid mistake or all idea is wrong?
Thanks for any help.

Query strings are like dictionary : {key, value} pairs. Therefore you cannot pass your class objects in query strings.
But, what you can do, is to pass this the id for your model object and then use that id to load your object on server.
Right now, you are working on a wrong notion ! :-)

One other option is to serialize / deserialize the object for example:
<a href="#Url.Action("Vote", "Ideas", new { id = item.Idea.Id, pageMetadata = JsonConvert.SerializeObject(Model.PageMetadata), numberOfVotes = 2 })">
in the controller:
public ActionResult Vote(string id,string pageMetadata, int numberOfVotes = 1)
var pageMetadataObj = JsonConvert.DeserializeObject<PageMetadata>(pageMetadata)
Note: this will expose your object properties to the browser and could add significant size to the webpage depending on the number and type of objects.

You can use Html.ActionLink method :
https://www.aspsnippets.com/Articles/Pass-Send-Model-from-View-to-Controller-using-ActionLink-in-ASPNet-MVC.aspx

Related

Passing several query parameters to a GET endpoint in .netcore web api

I have an application where there will be several parameters passed to my endpoint for searching, these parameters are not defined because they are dynamically generated so i cannot map it to a specific model. What would be the best way to map any query parameters into my GET endpoint?
[HttpGet]
public CustomResponse GetResults({something here that will map the parameters?})
{
//perhaps a dictionary? a collection of some sort?
}
Then I need to get all those keys and values and search the database for anything containing that and as i said it could be anything.
So I could pass something like?
/api/Merchandise/GetResults?sku=30021&cupsize=medium&color=red&location=south& {and all the dynamic fields which could be anything}
HttpRequest object has Query property that is an IQueryCollection and holds all passed query parameters.
In other words, in your action method you may do:
[HttpGet]
public CustomResponse GetResults()
{
var queryParams = HttpContext.Request.Query;
// directly get by name
var value1 = queryParams["parameter_name"];
// or queryParams.TryGetValue()
foreach (var parameter in queryParams)
{
string name = parameter.Key;
object value = parameter.Value;
}
}
You could map it to JObject, which is like a Dictionary.
Don't forget:
using Newtonsoft.Json;

Get route {id} value in view?

I known if I have something like /controller/action/{id} I can access id as a function parameter. But how would I access it via the view without using the viewbag?
You can pass that function parameter to the View as part of a model. The model can be staticly or dynamically typed. The example code below demonstrates how to pass the value as a property on a dynamic model.
public ActionResult Edit(string id)
{
dynamic model = new System.Dynamic.ExpandoObject();
model.Id = id;
return View(model);
}
You would access this value in the view as follows:
#Model.Id
You can parse the URL to get the ID when in the view:
var id = Request.Url.LocalPath.SubString(LastIndexOf("/",Request.Url.LocalPath)+1);
It will be put directly into the ViewBag.id or you can access it via ViewData["id"]. hey seem like the same object

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...
}
}

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.

Getting a strongly typed Model from MVC3 Helper

I've found a property of my helper that I think will give me access to the properties of my model, but I was hoping to get an instance of the model itself. I have a view with a strongly typed Model. One property of the model, is a collection of other models (TestModel). I would like to render each of the items in the collection in a standard way. So, my view code would look something like this.
#foreach(var testModel in #Model.Items){
#Html.DisplayViewerFor(#testModel)
}
My helper looks something like this.
public static MvcHtmlString DisplayViewerFor(this HtmlHelper<TestModel> helper, Expression<Func<TestModel>> expression, bool rightAligned = true) {
var modelData = helper.ViewData;
var prop = modelData[""];
var outterDiv = new TagBuilder("div");
outterDiv.AddCssClass(rightAligned ? "item-display-right" : "item-display");
//Create other markup using modelData here
//Would prefer to use an instance of TestModel
return new MvcHtmlString(outterDiv.ToString(TagRenderMode.EndTag));
}
It sounds like you want a value, not an expression.
Extend the non-generic HtmlHelper class and take a raw TestModel instance as a parameter.
You only need an expression tree if you want to find out the property name.

Resources