MVC - use C# to fill ViewBag with Json Action Result - c#

I have an MVC website with C# code behind. I am using an ActionResult, that returns Json.
I am trying to put something in the ViewBag but it doesn't appear to work.
The code looks like this -
public ActionResult GetStuff(string id)
{
ViewBag.Id = id;
stuff = new StuffFromDatabase(id);
return this.Json(stuff , JsonRequestBehavior.AllowGet);
}
The "id" does not appear go in the ViewBag.Id.
Can I put the id in the ViewBag this way? If not any suggestions on how I should do it?
Thanks!

Another solution can be this: if you want access "id" property after post action that return json result, you can return a complex object containing all data required:
public ActionResult GetStuff(string id)
{
ViewBag.Id = id;
stuff = new StuffFromDatabase(id);
return this.Json(new { stuff = stuff, id = id } , JsonRequestBehavior.AllowGet);
}
After, in json returned value, you can access all properties like in this example:
$.post(action, function(returnedJson) {
var id = returnedJson.id;
var stuff = returnedJson.stuff;
});

ViewBag is only available server-side. You are sending a json string back to the browser, presumably the browser then does something with it. You will have to send the id in the json response as follows:
return this.Json(new { Id = id, Data = stuff }, JsonRequestBehaviour.AllowGet);

You trying to set ViewBag.Id in Json result? ViewBag used in views, not in Json.
Added
As I can see from comments, then you trying to use it in javascript, you can do such things. Try this:
return this.Json(new {stuff, id} , JsonRequestBehavior.AllowGet);
Then you can access this data in javascript.

Related

.NET Passing List to Redirect Action [duplicate]

I want to pass more then one parameter from RedirectToAction method
how can I pass?
My One Action Method
[HttpPost, ActionName("SelectQuestion")]
public ActionResult SelectQuestion(string email,List<QuestionClass.Tabelfields> model)
{
List<QuestionClass.Tabelfields> fadd = new List<QuestionClass.Tabelfields>();
for (int i = 0; i < model.Count; i++)
{
if (model[i].SelectedCheckbox == true)
{
List<QuestionClass.Tabelfields> f = new List<QuestionClass.Tabelfields>();
fadd.Add(model[i]);
}
}
return RedirectToAction("Question", new { email = email, model = fadd.ToList() });
}
My another Action Method
[HttpGet]
public ActionResult Question(string email,List<QuestionClass.Tabelfields> model)
{
}
I am not getting values in model.
You cannot pass a collection of complex objects in urls when redirecting.
One possibility would be to use TempData:
TempData["list"] = fadd.ToList();
return RedirectToAction("Question", new { email = email});
and then inside the Question action:
var model = TempData["list"] as List<QuestionClass.Tablefields>;
The way that I solved this problem was to serialize the list to a JSON object using the JsonConvert method from the Newtonsoft.Json nuget package. Then the serialized list can be passed as a parameter and then deserialized again to re-create the original list.
So in your SelectQuestion method you would use this code:
return RedirectToAction("Question",
new {
email = email,
serializedModel = JsonConvert.SerializeObject(fadd.ToList())
});
And in your Question method, you would use this code to deserialize the object.
[HttpGet]
public ActionResult Question(string email, string serializedModel)
{
// Deserialize your model back to a list again here.
List<QuestionClass.Tabelfields> model = JsonConvert.DeserializeObject<List<QuestionClass.Tabelfields>>(serializedModel);
}
Important, this adds the model as a query string parameter to your url, so only do this with really simple small objects, otherwise your url will be too long.
This is probably not even active anymore, but I'll leave how I did it here to maybe help someone else.
I solved this using a simple Redirect instead of a RedirectToAction:
List<int> myList = myListofItems;
var list = HttpUtility.ParseQueryString("");
myList.ForEach(x => list.Add("parameterList", x.ToString()));
return Redirect("/MyPath?" + list);
Then, on your other method:
public ActionResult Action(List<int> parameterList){}
RedirectToAction method Returns an HTTP 302 response to the browser, which causes the browser to make a GET request to the specified action.
You should either keep the data in a temporary storage like TempData / Session . TempData uses Session as the backing storage.
If you want to keep it real Stateless, you should pass an id in the query string and Fetch the List of items in your GET Action. Truly Stateless.
return RedirectToAction("Question", new { email = email,id=model.ID });
and in your GET method
public ActionResult Question(string email,int id)
{
List<QuestionClass.Tabelfields> fadd=repositary.GetTabelFieldsFromID(id);
//Do whatever with this
return View();
}
Assuming repositary.GetTabelFieldsFromID returns a List of TabelFields from the Id

ASP.NET MVC - Add Query String Value to RedirectToAction in Controller

I have an ASP.NET MVC app. My app is using T4MVC. In my controller, I need to redirect from one action to another. When I do this, I want to append a query string value. I can successfully redirect without the query string value, but I've been unsuccessful applying a query string value. My actions look like this:
[HttpPost]
[ValidateAntiForgeryToken]
public virtual ActionResult Action1()
{
return RedirectToAction(MVC.MyController.Action2().AddRouteValue("id", "5"));
}
[Route("action-2")]
public virtual ActionResult Action2(string input)
{
ViewBag.Input = input;
return View(viewModel);
}
The Action2 works fine when I visit ./action-2. I can also successfully POST to Action1. But, when the redirect doesn't work. I notice in the address bar the following:
/MyController/id
Why? How do I fix this? I just want to redirect back to Action2 but this time with a query string parameter added. What am I missing?
You need to specify the parameter by the name in the action (in this case "input") in order for it to work, see below:
return redirectToAction(MVC.MyController.Action2().AddRouteValue("input", "5"));
or alternatively:
return RedirectToAction("Action2", "MyController", new { input = "myInput"});
I try in following way and it works fine for me.
return RedirectToAction("Index", "CustomBuilder", new { usern = "admin" });

Set Viewbag before Redirect

Is it possible to set the ViewBag before I call a redirection?
I want something like:
#ViewBag.Message="MyMessage";
RedirectToAction("MyAction");
When you use redirection, you shall not use ViewBag, but TempData
public ActionResult Action1 () {
TempData["shortMessage"] = "MyMessage";
return RedirectToAction("Action2");
}
public ActionResult Action2 () {
//now I can populate my ViewBag (if I want to) with the TempData["shortMessage"] content
ViewBag.Message = TempData["shortMessage"].ToString();
return View();
}
You can use the TempData in this situation.
Here is some explanation for the ViewBag, ViewData and TempData.
I did like this..and its working for me...
here I'm changing password and on success I want to set success message to viewbag to display on view..
public ActionResult ChangePass()
{
ChangePassword CP = new ChangePassword();
if (TempData["status"] != null)
{
ViewBag.Status = "Success";
TempData.Remove("status");
}
return View(CP);
}
[HttpPost]
public ActionResult ChangePass(ChangePassword obj)
{
if (ModelState.IsValid)
{
int pid = Session.GetDataFromSession<int>("ssnPersonnelID");
PersonnelMaster PM = db.PersonnelMasters.SingleOrDefault(x => x.PersonnelID == pid);
PM.Password = obj.NewPassword;
PM.Mdate = DateTime.Now;
db.SaveChanges();
TempData["status"] = "Success";
return RedirectToAction("ChangePass");
}
return View(obj);
}
Taken from here
Summary
The ViewData and ViewBag objects give you ways to access those extra pieces of data that go alongside your model, however for more complex data, you can move up to the ViewModel. TempData, on the other hand, is geared specifically for working with data on HTTP redirects, so remember to be cautious when using TempData.
Or you can use Session for alternative:
Session["message"] = "MyMessage";
RedirectToAction("MyAction");
and then call it whenever you need.
UPDATE
Also, as what #James said in his comment, it would be safe to nullify or clear the value of that specific session after you use it in order to avoid unwanted junk data or outdated value.

How to pass Viewdata value to masterpage in Razor MVC4

I use Directoryservices for login in My page. I need to pass the username to my masterpage to display the username in all the pages.
I got the username and stored it in a ViewData. How to pass the viewdata value in masterpage.
My code :
[HttpPost]
public ActionResult Index(LoginModels model)
{
if (ModelState.IsValid)
{
string DisplayUserName = string.Empty;
string LoginUser = model.Userid;
string LoginPassword = model.Password;
string name = model.UserName
if (ValidateActiveDirectoryLogin(LoginUser, LoginPassword, out DisplayUserName) == true)
{
model.UserName = DisplayUserName;
ViewData["UserName"] = "Welcome" + DisplayUserName;
return RedirectToAction("Index", "MPP", new { UserID = LoginUser });
}
else
{
ModelState.AddModelError("","Invalid Username or Password");
}
}
return View();
}
In Layout page :
#{ #ViewData["UserName"] }
I tried the following way to display the Username. But it throws nullexception.
EDIT :
#foreach (var m in IEnumerable<SampleECommerce.Models.LoginModels>)ViewData["UserName"])
{
#m.UserName
}
There are some misunderstandings, like if you set ViewData["UserName"] to a string value you get a IEnumerable<SampleECommerce.Models.LoginModels>. Here is another solution:
Put this to layout page:
<span>#{Html.RenderAction("actionname", "controllername");}</span>
And in related action:
public ActionResult actionname() {
string result = getusername();
return Content(result);
}
[NoneAction]
private string getusername(){
return (Membership.GetUser()!= null) ? Membership.GetUser().UserName : "Guest";
}
Try it without the extra #, i.e.
#{ ViewData["UserName"] }
Firs you need to change your syntax to:
#(ViewData["UserName"])
That's probably the best (of a bad bunch). Realistically you should be looking to push your user into the User property of your pages via the User property of your controllers (typically in an authorization attribute where, perhaps, you read a cookie) - that way you don't rely on type-unsafe ViewData and magic strings for something that you're going to be using on every page.
But anyway... if the view is rendering because of the last return View(); line then what you're trying to do will work if you change your syntax as I've shown.
If not, and it's when you do return RedirectToAction("Index", "MPP", new { UserID = LoginUser }); then you need to push the UserName into TempData and then read it back at the start of the Index action on your MPP controller:
So:
TempData["UserName"] = "Welcome " + DisplayUserName;
return RedirectToAction("Index", "MPP", new { UserID = LoginUser });
And then at the start of your Index method you need to pull the value back out of TempData:
public class MPPController {
public ActionResult Index(){
ViewData["UserName"] = TempData["UserName"];
}
}
Why do you have to do this? Because RedirectToAction doesn't render a page - it tells the client to make a different request to a new Url - thus any ViewData or model or whatever is thrown away as far as the server is concerned. TempData is there to provide temporary storage between two successive requests only - thus it works well for the RedirectToAction scenario.
Like I say though - this really is a poor way to persist your user information from controller to view and you should seriously rethink it as a matter of urgency.
in layout page:
<span>#{Html.RenderAction("actionname", "controllername");}</span>
in controller store a session variable
[HttpPost]
public ActionResult Index(LoginModels model)
{
Session["username"] = model.UserName;
//remaining code
}
add one more function
public ActionResult actionname() {
return Content(Session["username"]);
}
so here we dont need additional functions.

Asp.Net MVC - Blank model not returning blank data

I have a form which a user can fill in x times with the data they want too. The form is posted to the following Action.
[HttpPost]
public ActionResult Manage(ProductOptionModel DataToAdd)
{
if (!ModelState.IsValid)
{
return View(DataToAdd);
}
var ProdServ = new ProductService();
if (DataToAdd.ID != 0)
{
//Edit Mode.
DataToAdd = ProdServ.EditProductOption(DataToAdd);
ViewData["Message"] = "Option Changes Made";
}else
{
//Add
DataToAdd = ProdServ.AddProductOption(DataToAdd);
ViewData["Message"] = "New Option Added";
}
var RetModel = new ProductOptionModel() {ProductID = DataToAdd.ProductID};
return View(RetModel);
}
So at the bottom I blank the model (Leaving just the required field) and then return to the view. However the view holds the data from the previously submitted form.
Any ideas why? I have debugged the code and checked that the RetModel variable is empty.
Html helpers work this way when a view is returned on HTTP POSTs. They prefer post data over model values.
Use Post/Redirect/Get
That's why I suggest you use the Post/Redirect/Get pattern that's very well supported in Asp.net MVC. Your controller actions should redirect to some GET action after POST has successfully completed as it is in your case.
public ActionResult Process()
{
return View(new Data { Id = -1 });
}
[HttpPost]
public ActionResult Process(Data data)
{
if (!this.ModelState.IsValid)
{
return View(data);
}
new MyService().ProcessData(data);
return RedirectToAction("Process");
}
And if you display all previously entered data you can provide those in in the GET action or transfer them from POST to GET action using TempData dictionary.
This is because the build in input helpers will look at the posted data first and use those values if they exist. Then it will look at the model.

Categories