Passing Model from One Controller to Another - asp.net-mvc

I need to pass a View Model from one controller to another controller. I used the below statement.
return RedirectToAction("FillNewSession", "Account", new { LoginResult = loginResult });
LoginResult is an object of the model "UserLoginProperties". FillNewSession controller is below.
public ActionResult FillNewSession(UserLoginProperties LoginResult)
{
Session["UserID"] = LoginResult.UserID.ToString();
Session["LoginID"] = LoginResult.LoginID;
Session["UserFullName"] = LoginResult.UserFullName;
Session["UserTypeID"] = LoginResult.UserTypeID;
Session["UserRefNo"] = LoginResult.UserRefNo;
Session["UserNRIC"] = LoginResult.UserNRIC;
return Redirect("~/index.aspx");
}
Problem is when "FillNewSession" controller is executed the passed parameter "LoginResult" is null.
Please Help.

If you want to pass an object through a redirect call you need to send all the properties of the object one by one, as illustrated below. You can't just pass the object as it is.
public class UserLoginProperties
{
public string UserID { get; set; }
public string LoginID { get; set; }
}
public class HomeController : Controller
{
public ActionResult Index()
{
var prop = new UserLoginProperties(){ LoginID = "123", UserID = "abc"};
return RedirectToAction("OtherAction", new { UserID=prop.UserID, LoginID=prop.LoginID });
}
public ActionResult OtherAction(UserLoginProperties prop)
{
// do whatever you want with it here
}
}

Related

How to pass more than one object to the view in mvc?

I want to pass more than one object in the view. I have two object. One name is "Caller" and one Name is "Receiver". I am new in MVC. This is my action method.
public ActionResult IsActiveCaller(int id)
{
var caller = new CallerService().getCallerById(id);
if(caller.active)
{
var reciver= new reciverService().getReviverTime(caller.dialNo);
return (caller ) // here i also want to send reciver to view
}
return View();
}
Is there any way to send more than object in view?
Yes you can do this. There are multiple ways to do this.
1) You can use viewBag to pass the data or object into view.
You can see here to see how to use viewBag in mvc
2) you can use ViewData but it is not a good approach.
3) you can make ViewModel like as below (recomended)
public class callerReciver
{
public Caller caller {set;get;}
pblic Reciver eciver {set;get;}
}
Now pass callerReciver to view.You can access both object.hope you will understand.
4) Another way is to use partial view.You can make partial view to use more than one object in same view.
You can use a View Model:
public class MyViewModel
{
public Caller Caller { get; set; }
public Receiver Receiver { get; set; }
}
Then you can populate the view model this way:
public ActionResult IsActiveCaller(int id)
{
var caller = new CallerService().getCallerById(id);
var vm = new MyViewModel {
Caller = caller
};
vm.Receiver = caller.active ? new reciverService().getReviverTime(caller.dialNo) : null;
return View(vm);
}
View:
#model MyViewModel
<h1>#Model.Caller.Title</h1>
#if(Model.Receiver != null) {
<h1>#Model.Receiver.Title</h1>
}
The cleanest way is to pass by a view model :
ViewModel
public class MyViewModel {
public Caller MyCaller { get;set; }
public Receiver MyReceiver { get;set; }
}
Controller
public ActionResult IsActiveCaller(int id)
{
var caller = new CallerService().getCallerById(id);
var viewModel = new MyViewModel();
viewModel.MyCaller = caller;
if(caller.active)
{
var reciver= new reciverService().getReviverTime(caller.dialNo);
viewModel.MyReceiver = reciver;
}
return View(viewModel);
}
View
#model MyViewModel
<h1>#Model.MyCaller.Id</h1>
<h1>#Model.MyReceiver.Id</h1>

Cant pass data from one method to another in same controller

I am developing MVC application.
I am trying to pass the data from one method to another method in same controller.
But data doesn't pass properly...
Please check below code... I am trying to pass the Product list from Create to Save data method.
namespace StockWatchScreen.Controllers
{
public class OrderController : Controller
{
public class OrderProduct
{
public string SectionCode { get; set; }
public double Size { get; set; }
public double Thickness { get; set; }
public double Length { get; set; }
public double Quantity { get; set; }
}
public ActionResult Create()
{
List<OrderProduct> oProductList = new List<OrderProduct>();
OrderProduct oProduct = new OrderProduct();
oProduct.SectionCode = "123";
oProduct.Length = "123";
oProduct.Size = "123";
oProduct.Thickness = "123";
oProduct.Quantity = "123";
oProductList.Add(oProduct);
}
return RedirectToAction("SaveData", oProductList);
}
public ActionResult SaveData(List<OrderProduct> oProductList)
{
ViewBag.ProductList = oProductList;
ViewBag.OrderNo = "12321#";
return View();
}
}
}
}
In SaveData method, oProductList list shows always null.
What is reason ?
You need to return :return SaveData( oProductList); .You don't need to return RedirectToAction , and try to avoid using TempData["oProduct"] using TempData in mvc is not good practice.
Using AjaxBeginForm you on succes you can get result return SaveData( oProductList);and put it where you want .also you can use UpdateTargetId.
You can't send model like this in RedirectToAction, you should use tempdata for this communicating between actions like this
public ActionResult Create()
{
List<OrderProduct> oProductList = new List<OrderProduct>();
OrderProduct oProduct = new OrderProduct();
oProduct.SectionCode = "123";
oProduct.Length = "123";
oProduct.Size = "123";
oProduct.Thickness = "123";
oProduct.Quantity = "123";
oProductList.Add(oProduct);
}
TempData["oProduct"] = oProductList;
return RedirectToAction("SaveData");
}
And in the recieving controller
public ActionResult SaveData(List<OrderProduct> oProductList)
{
ViewBag.ProductList = TempData["oProduct"] as List<OrderProduct> ;
ViewBag.OrderNo = "12321#";
return View();
}
This is because RedirectToAction is doing a 301 redirection, and it is actually the client initiating a Get request to the /SaveData action.

Model property is empty

I am trying to move from webForms to Asp.net-MVC and have some problems. I am trying to figure why this is not working, I am getting this error: "Object reference not set to an instance of an object"
I have the class 'Pages':
namespace _2send.Model
{
public class Pages
{
public string PageContent { get; set; }
public string PageName { get; set; }
public int LanguageId { get; set; }
}
}
I am inserting the value to 'Pages.PageContent' property with this class:
namespace _2send.Model.Services
{
public class PagesService : IPagesService
{
public void GetFooterlinksPage()
{
DB_utilities db_util = new DB_utilities();
SqlDataReader dr;
Pages pages = new Pages();
using (dr = db_util.procSelect("[Pages_GetPageData]"))
{
if (dr.HasRows)
{
dr.Read();
pages.PageContent = (string)dr["PageContent"];
dr.Close();
}
}
}
The Controller method looks like this:
private IPagesService _pagesService;
public FooterLinksPageController(IPagesService pagesService)
{
_pagesService = pagesService;
}
public ActionResult GetFooterLinksPage()
{
_pagesService.GetFooterlinksPage();
return View();
}
I am trying to write the property in the view like this:
#model _2send.Model.Pages
<div>
#Model.PageContent;
</div>
When debugging, the method is fired and the dataReader is inserting the value to the 'PageContent' property, but I am still getting this error from the view.
Thanks!
return View();
You didn't pass a model.
You need to pass the model as a parameter to the View() method.
You need to rewrite service method to return Pages:
public Pages GetFooterlinksPage()
{
DB_utilities db_util = new DB_utilities();
Pages pages = new Pages();
using (var dr = db_util.procSelect("[Pages_GetPageData]"))
{
if (dr.HasRows)
{
dr.Read();
pages.PageContent = (string)dr["PageContent"];
return pages;
// Because you use using, you don't need to close datareader
}
}
}
And then rewrite your action method:
public ActionResult GetFooterLinksPage()
{
var viewmodel = _pagesService.GetFooterlinksPage();
return View(viewmodel);
}
You can return a model:
var viewmodel = new _2send.Model.Pages().
//here you configure your properties
return View(viewmodel);

Validate multi-field in [MetadatType(typeof(myClass)]

I have a model class with [MetadataType(typeof(ThisEntityMetaData))] and [Bind(...)] annotations. I need to validate post back combined property values and a route parameter(viewType). The viewType is not a property of the entity class. So far I can only do this validation in [post] of the action. I'd like to do this validation in the entity class or the ThisEntityMetaData class. How can I do that? Thanks.
[HttpPost]
[ActionName("Create")]
[AcceptParameter(Name = "Save", Value = "Save")]
[ValidateInput(false)]
public ActionResult Create(int id, thisViewModel newViewModel,
string cancel, enumViewType viewType)
{
/* code omitted */
switch(viewType)
{
case enumViewType.OutAndNoReturn:
case enumViewType.OutAndReturn:
if(!thisEntity.Source.HasValue || !thisEntity.Reason.HasValue)
ViewData["Message"] = "Source, Reason are required.";
break;
case enumViewType.DirectOut:
case enumViewType.IndirectOut:
if ((!thisEntity.Source.HasValue || !thisEntity.Reason.HasValue ||
!thisEntity.Desired.HasValue))
{
thisEntity.ShowOutBlock = true;
ViewData["Message"] = "Source, Reason, Desired are required.";
return View(thisEntity);
}
break;
}
/* code omitted */
}
The viewType is not a property of the entity class.
You could use a real view model, not something that you have named view model but actually is not a view model at all:
[HttpPost]
[ActionName("Create")]
[AcceptParameter(Name = "Save", Value = "Save")]
[ValidateInput(false)]
public ActionResult Create(thisViewModel newViewModel)
{
...
}
where thisViewModel obviously contains everything you need:
[MetadataType(typeof(ThisEntityMetaData))]
public class thisViewModel
{
public int Id { get; set; }
public string Cancel { get; set; }
public enumViewType ViewType { get; set; }
...
}
Now inside your ThisEntityMetaData feel free to validate whatever you want in this view model.

How to get Controller Name and its properties in another class?

I am developing a MVC application.
I want to send a controller for validating purpose to Validation class.
That class will validate the controllers properties and send the result.
I am not gettting, how to get name and properties of the controller after
getting it in class.
Below code is the Controller class code and I send this controller to class named validation class.
[HttpPost]
public ActionResult Create(Location location)
{
if (ModelState.IsValid)
{
Validations v = new Validations();
Boolean ValidProperties = true;
//Sends the controller to Validation class
v.ValidProperty(this);
if (ValidProperties == true)
{
db.Locations.Add(location);
db.SaveChanges();
return RedirectToAction("Index");
}
}
}
And Below code is the class named Validations where I want to validate the controller .
Now I am not getting how to get the name of controller and its properties.
public class Validations
{
string PropertName;
public void ValidProperty(Controller ctr)
{
var name1 = ctr;
string s = ctr. ????????
//How to get Controller Name and its properties ?
}
}
use reflection to get name as:
var name = this.GetType().Name;
Or you can create a custom base controller of your choice, add properties, methods to it and deal with derived controllers as:
public abstract class BaseController : Controller
{
// add other properties as needed
public abstract string Name { get; protected set; }
public virtual void ValidProperty()
{
string s = Name;
//something esle
}
}
public class YourController : BaseController
{
private string _name;
public override string Name
{
get { return _name; }
protected set { _name = "Your_Name"; }
}
[HttpPost]
public ActionResult Create(Location location)
{
if (ModelState.IsValid)
{
bool validProperties = true;
// Deals with a base controller method
ValidProperty();
// or something like this, if you prefer
var controller = (BaseController) this;
Validations v = new Validations();
//Sends the controller to Validation class
v.ValidProperty(controller);
if (validProperties)
{
db.Locations.Add(location);
db.SaveChanges();
return RedirectToAction("Index");
}
}
return Content(string.Empty);
}
}

Resources