How to pass value from one action to another action having different views in mvc3 - asp.net-mvc-3

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

Related

Passing data from Controller to model in MVC 3

is there a way to pass data from controller to model?
the scenario of my project is that, it has two tables in database, and in View there are two text boxes , the data of one text box is save to one table while data of another table is save to another table , i want to show the data of both tables in another single View . for that reason i want to send both textbox values from controller to model then want to show the data from that model to the view.
can someone please help how can i implement it ?
You need to create a view model and use that. view model's are simple POCO classes which are specific to the view.
public class CustomerInfo
{
public string Name {set;get;}
public string AddressLine {set;get;}
}
And in your GET Action, you can create an object of this, read the data from 2 tables and set the property values of our view model and send to the view
public ActionResult View(int id)
{
var vm = new CustomerInfo();
var db=new YourDbContext();
var customer=db.GetCustomer(id); // read from first table
var address=db.GetAddress(id); // read from second table
vm.Name = customer.FirstName;
vm.AdddressLine = address.AddressLine1;
return View(vm);
}
And your view will be strongly typed to this view model
#model CustomerInfo
<h2>#Model.Name</h2>
<h3>#Model.AddressLine1</h3>
If you are trying to save this information to the db tables, You may have a form in your view
#model CustomerInfo
#using(Html.BeginForm("Edit","Home"))
{
<label>Name</label> #Html.TextBoxFor(f=>f.Name)
<label>Name</label> #Html.TextBoxFor(f=>f.AddressLine)
<input type="submit" />
}
and in your HttpPost action
[HttpPost]
public ActionResult Edit(CustomerInfo model)
{
// read the values from model and save to 2 tables
var c=new Customer { FirstName=model.Name};
var a=new Address{ AddressLine1=model.AddressLine};
var db=new YourDbContext();
db.Customers.Add(c);
db.Addresses.Add(a);
db.SaveChanges();
return RedirecToAction("Success");
}
If you want to save a collection of items, You may refer this answer or this.

How could i dynamically bind data in checkbox in mvc3 razor

I am working in mvc3 razor.
i want checkbox input in razor view for all catagories stored in database.
how could i bind it? please help
Suppose your model is having a field to hold all the checkbox text like.
public class MyClass
{
public string SelectedOptions {get;set;}
public List<String> CheckList {get;set;}
}
Write a controller Action method like
public ActionResult ShowCheckBoxList()
{
MyClass Options= new MyClass();
Options.CheckList = new List<String>();
// Here populate the CheckList with what ever value you have to
// either if you are getting it from database or hardcoding
return View(Options);
}
you have to create a view by right clicking the above method and choose Add View. Make sure you keep the name same as the method name also you the strongly typed view by choosing the MyClass Model from the dropDown, scaffolding template is optional use it as per your scenario.
Now in your View you can use this populated check box text as
#foreach(var optionText in Model.CheckList)
{
#Html.CheckBox(#Model.SelectedOptions, false, new {Name = "SelectedOptions", Value = #optionText})
#Html.Label(#optionText , new { style = "display:inline;" })
}
Keep this in a form and make sure you also specify a Action to be called on post of the form.
Make your action name same as the previous action (it is [GET] meaning before post), Now we create same method for [POST]
[HTTPPOST]
public ActionResult ShowCheckBoxList(MyClass data) // here you will get all the values from UI in data variable
{
//data.SelectedOptions will have all the selected values from checkbox
}

Is there any way to pass a whole model via html.actionlink in ASP.NET MVC 3?

How do I pass a whole model via html.actionlink or using any other method except form submission? Is there any way or tips for it?
Though it's not advisable in complex cases, you can still do that!
public class QueryViewModel
{
public string Search { get; set; }
public string Category { get; set; }
public int Page { get; set; }
}
// just for testing
#{
var queryViewModel = new QueryViewModel
{
Search = "routing",
Category = "mvc",
Page = 23
};
}
#Html.ActionLink("Looking for something", "SearchAction", "SearchController"
queryViewModel, null);
This will generate an action link with href like this,
/SearchController/SearchAction?Search=routing&Category=mvc&Page=23
Here will be your action,
public ViewResult SearchAction(QueryViewModel query)
{
...
}
No, you cannot pass entire complex objects with links or forms. You have a couple of possible approaches that you could take:
Include each individual property of the object as query string parameters (or input fields if you are using a form) so that the default model binder is able to reconstruct the object back in the controller action
Pass only an id as query string parameter (or input field if you are using a form) and have the controller action use this id to retrieve the actual object from some data store
Use session
You could use javascript to detect a click on the link, serialize the form (or whatever data you want to pass) and append it to your request parameters. This should achieve what you're looking to achieve...

Is it possible to pass object as route value in 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

MVC ddl value after postback

I have a ddl which is populated with hours of day 01-23. This is on a form which is used to book an item of equipment. The hour is populated to a db field. The issue is this, when the booking form is opened to alter the time the ddl shows the hour that was booked, when changed though and the form is submitted the value passed on post is the initial value from db not the new selected hour.
this is the basic pieces of code. any idea why the newly selected ddl value is not passed to the model??
View
<%= Html.DropDownList("ddl_Hour", Model.ddlHour,
new { #class = "DropDown", style = "width: 40px” })%>
Model
private string _ddlHourSelectedValue = "0";
public SelectList ddlHour
{
get
{
return (new System.Web.Mvc.SelectList(_ddlHour, "intValue", "Text", Convert.ToInt32(_ddlHourSelectedValue)));
}
}
public string ddlHourSelectedValue
{
get
{
return _ddlHourSelectedValue;
}
set
{
_ddlHourSelectedValue = value;
}
}
param[6] = new SqlParameter("#Timeslot", ddlHourSelectedValue);
The field in your view is called "ddl_Hour" However is there a variable in your Model with the same name? Otherwise the MVC framework will not automatically populate the value in the model.
Two ways you could go about this.
1
In your controller methods that accepts a post, you can add the parameter: FormCollection fc to the method. This key value pair collection will allow you to fetch results from fields in the post data like so:
string selectedValue = fc["ddl_Hour"];
2
Or you can modify your model to include a variable with the same name as the drop down list so that it is automatically populated for you.
public string ddl_Hour { get; set; }
You should then be able to access the result of the drop down list selection on post from that variable.

Resources