Post-Redirect-Get issue in MVC3 - asp.net-mvc-3

I need to use Post-Redirect-Get to show data, which I entered in "Information" page on "Index" page. I have the following methods, but it doesn't work. It doesn't even redirect me on submit. What am I doing wrong?
public class HomeController : Controller
{
public ActionResult Index()
{
return View();
}
public ActionResult About()
{
return View();
}
public ActionResult Information()
{
return View();
}
//Get info
[HttpGet]
public ActionResult Submit(Models.Information FirstName,
Models.Information LastName,
Models.Information DateOfBirth,
Models.Information HourOfBirth,
Models.Information NumberOfKids,
Models.Information Emso,
Models.Information Email,
Models.Information PlaceOfBirth)
{
if (ModelState.IsValid)
{
Models.Information info = new Models.Information();
info.FirstName = FirstName.ToString();
info.LastName = LastName.ToString();
info.DateOfBirth = Convert.ToDateTime(DateOfBirth);
info.HourOfBirth = Convert.ToDateTime(HourOfBirth);
info.NumberOfKids = Convert.ToInt32(NumberOfKids);
info.Emso = Emso.ToString();
info.Email = Email.ToString();
info.PlaceOfBirth = PlaceOfBirth.ToString();
TempData["info"] = info;
return RedirectToAction("Summary");
}
return View();
}
//Show info
[HttpPost]
public ActionResult Post(Models.Information info)
{
info.FirstName = ViewData["FirstName"].ToString();
info.LastName = ViewData["LastName"].ToString();
info.DateOfBirth = Convert.ToDateTime(ViewData["DateOfBirth"]);
info.HourOfBirth = Convert.ToDateTime(ViewData["HourOfBirth"]);
info.NumberOfKids = Convert.ToInt32(ViewData["NumberOfKids"]);
info.Emso = ViewData["Emso"].ToString();
info.Email = ViewData["Email"].ToString();
info.PlaceOfBirth = ViewData["PlaceOfBirth"].ToString();
return View();
}
}
I try to show data on Index page like this:
First name: <input type='text' runat="server" value="#ViewData["FirstName"]" /><br />

Your code looks sort of confusing to me and I am not sure what you are trying to accomplish. But first, let's use an example on what I think you are trying to accomplish.
User enters information on the information action/view
(POST)This is POSTed to a controller/action which then verifies the model and puts in into the ViewData (REDIRECT TO STEP 3)
(GET)You want to redisplay this data on a summary page.
Under those assumptions, lets clean up your code a bit, leverage the use of the ViewData and TempData objects and see if we can make this work.
Information Action
public ActionResult Information()
{
//In a strongly typed view, typically you would send an empty model
//so the model binder/Html.Input helpers have something to bind to
return View(new Models.Information());
}
Information POST to handle incoming data
[HttpPost]
public ActionResult Information(Models.Information info)
{
//Yup - you can use the same action name as the GET action above
//You can name this anything you want, but I typically keep the same names so
//I know where the data came from
//I think your assignments are backwards. info came into the controller action
//You want to save this as ViewData. Also, let's do that in one line of code
//And since we are redirecting, lets use the TempData dictionary
//Notice the method type decorator above [HttpPost]. This is the P in PRG (Post)
if(modelState.IsValid()){
TempData["info"] = info;
//Notice the name of the ActionMethod below. The is the R in PRG (Redirect)
return RedirectToAction("Summary");
}
//There were errors, lets send back to the Information view
return View(info);
}
Summary Action
public ActionResult Summary()
{
//We were redirected here, and this is a GET method. This is the G in PRG
//(GET)
//lets go ahead and set the TempData stuff to a model, it just looks nicer on
//the view
var model = TempData["info"];
return View(model);
}
As for the views, here is a snippet of what each might look olike
Information View
#model Models.Information
#{using(Html.BeginForm()){
#Html.LabelFor(x=>x.FirstName)<br/>
#Html.TextBoxFor(x=>x.Firstname)
//Repeat for each property
<input type="Submit" value="Submit"/>
}}
Summary View
#model Models.Information
#Html.LabelFor(x=>x.FirstName)<br/>
#Html.DisplayFor(x=>x.Firstname)
//Repeat for each property

Related

Post selected dropdown to controller MVC using AJAX or other way

I need to post the selected item's id from dropdown to post method of same controller and the render the content in same view
PLease help me fast :(
My View
#Html.DropDownListFor(x => x.hotelmodel.SelectedHotelId, Model.hotelmodel.DrpHotelList)
<div>
<p>#Model.percentageoccupied</p>
<p>#Model.Revenue</p>
<p>#Model.UnSold</p>
<div>
MY HttpGetMethod
[HttpGet]
public ActionResult Counter()
{
var personid = ((PersonModel)Session["PersonSession"]).PersonId;
var model = new CounterforModel();
model.hotelmodel.DrpHotelList = iCommonservice.GetHotelListByPersonId(personid);
return View(model);
}
My HttpPostMethod
[HttpPost]
public ActionResult Counter(int id)
{
var result = iCommonservice.LoadCounter(id);
model.percentageoccupied = Convert.ToInt32(result[0].percentageoccupied);
model.Revenue = Convert.ToDecimal(result[0].Revenue);
model.UnSold = Convert.ToInt32(result[0].UnSold);
return View(model);
}
In your POST method pass your View Model as parameter. Then you can use the posted hotelModel.SelectedHotelId for what you need, update the model values and pass your updated model to the View.
public ActionResult Counter(CounterforModel model)
{
var result = iCommonservice.LoadCounter(model.hotelmodel.SelectedHotelId);
model.percentageoccupied = Convert.ToInt32(result[0].percentageoccupied);
model.Revenue = Convert.ToDecimal(result[0].Revenue);
model.UnSold = Convert.ToInt32(result[0].UnSold);
return View(model);
}
If you want, you can use #Ajax.BeginForm() or jQuery .ajax() to make an ajax call to your action. You can look here.

send data between actions with redirectAction and prg pattern

how can i send data between actions with redirectAction??
I am using PRG pattern. And I want to make something like that
[HttpGet]
[ActionName("Success")]
public ActionResult Success(PersonalDataViewModel model)
{
//model ko
if (model == null)
return RedirectToAction("Index", "Account");
//model OK
return View(model);
}
[HttpPost]
[ExportModelStateToTempData]
[ActionName("Success")]
public ActionResult SuccessProcess(PersonalDataViewModel model)
{
if (!ModelState.IsValid)
{
ModelState.AddModelError("", "Error");
return RedirectToAction("Index", "Account");
}
//model OK
return RedirectToAction("Success", new PersonalDataViewModel() { BadgeData = this.GetBadgeData });
}
When redirect you can only pass query string values. Not entire complex objects:
return RedirectToAction("Success", new {
prop1 = model.Prop1,
prop2 = model.Prop2,
...
});
This works only with scalar values. So you need to ensure that you include every property that you need in the query string, otherwise it will be lost in the redirect.
Another possibility is to persist your model somewhere on the server (like a database or something) and when redirecting only pass the id which will allow to retrieve the model back:
int id = StoreModel(model);
return RedirectToAction("Success", new { id = id });
and inside the Success action retrieve the model back:
public ActionResult Success(int id)
{
var model = GetModel(id);
...
}
Yet another possibility is to use TempData although personally I don't recommend it:
TempData["model"] = model;
return RedirectToAction("Success");
and inside the Success action fetch it from TempData:
var model = TempData["model"] as PersonalDataViewModel;
You cannot pass data between actions using objects, as Darin mentioned, you can only pass scalar values.
If your data is too large, or does not consist only of scalar values, you should do something like this
[HttpGet]
public ActionResult Success(int? id)
{
if (!(id.HasValue))
return RedirectToAction("Index", "Account");
//id OK
model = LoadModelById(id.Value);
return View(model);
}
And pass that id from RedirectToAction
return RedirectToAction("Success", { id = Model.Id });
RedirectToAction method returns an HTTP 302 response to the browser, which causes the browser to make a GET request to the specified action. So you can not pass complex objects like you calling other methods with complex objects.
Your possible solution is to pass an id using with the GET action can build the object again. Some thing like this
[HttpPost]
public ActionResult SuccessProcess(PersonViewModel model)
{
//Some thing is Posted (P)
if(ModelState.IsValid)
{
//Save the data and Redirect (R)
return RedirectToAction("Index",new { id=model.ID});
}
return View(model)
}
public ActionResult Index(int id)
{
//Lets do a GET (G) request like browser requesting for any time with ID
PersonViewModel model=GetPersonFromID(id);
return View(id);
}
}
You can keep data (The complex object) between This Post and GET request using Session also (TempData is internally using session even). But i believe that Takes away the purity of PRG Pattern.

assigning variables in the View in ASP MVC 3

Actually I'm very new to ASP.NET MVC and I need your help.
Here I have some Create Method that takes an argument from the URL to use it as id:
in 'vote' controller :
public ActionResult Create(int id)
{
Meeting meeting = db.Meetings.Find(id); // get the object
ViewBag.meetingID = meeting.meetingID; // get its id and assign it to a ViewBag
return View();
}
and I would like to do something like :
vote.meetingID = #ViewBag.meetingID
in the model so that is directly assgin this property without excplicitely typing it from the HTML view (I mean #Html.EditorFor(model=>meetingID) )
The question is not that clear, but try this.
You could pass the entire model to the view.
Controller:
public ActionResult Create(int id)
{
Meeting meeting = db.Meetings.Find(id); // get the object
ViewData["myMeeting"] = meeting;
return View();
}
To use in the view you can declare it as a variable at the top of the view:
Declare:
#
{
var meetingData = ViewData["myMeeting"] as Meeting;
}
Usage:
<div>
#meetingData.meetingID
</div>

Invalid ModelState with PartialViews

I have the following action
[GET("Foo")]
public virtual ActionResult Foo()
{
return View(new FooViewModel());
}
the view for this action calls this partial view
#{ Html.RenderAction(MVC.FooBar.AddFoo()); }
with controller actions
[ChildActionOnly]
[GET("Foo/Add")]
public virtual ActionResult AddFoo()
{
var viewModel = new AddFooViewModel();
return PartialView(viewModel);
}
[POST("Foo/Add")]
public virtual ActionResult AddFooPost(AddFooViewModel viewModel)
{
// If ModelState is invalid, how do I redirect back to /Foo
// with the AddFooViewModel ModelState intact??
if (!ModelState.IsValid)
return MVC.FooBar.Foo();
// ... persist changes and redirect
return RedirectToAction(MVC.FooBar.Foo());
}
If somebody submits the AddFoo form with ModelState errors, I want the POST action to redirect back to /Foo and show the AddFoo partial view with the ModelState errors. What's the best approach to handle this?
I think you could achieve that in 2 ways:
Using session state
Passing your data using querystring params
I prefer the second option.
I ended up putting the viewmodel into TempData like this with the ModelStateToTempData attribute on the controller
[ChildActionOnly]
[GET("Foo/Add")]
public virtual ActionResult AddFoo()
{
var viewModel = TempData["AddFooViewModel"] as AddFooViewModel ?? new AddFooViewModel();
return PartialView(viewModel);
}
[POST("Foo/Add")]
public virtual ActionResult AddFooPost(AddFooViewModel viewModel)
{
// If ModelState is invalid, how do I redirect back to /Foo
// with the AddFooViewModel ModelState intact??
if (!ModelState.IsValid)
{
TempData["AddFooViewModel"] = viewModel;
return RedirectToAction(MVC.FooBar.Foo());
}
// ... persist changes and redirect
return RedirectToAction(MVC.FooBar.Foo());
}

RedirectToAction after validation errors

If I have the usual Edit actions, one for GET to retrieve an object by it's ID and to display it in an edit form. The next for POST to take the values in the ViewModel and update the object in the database.
public virtual ActionResult Edit(int id)
[HttpPost]
public ActionResult Edit(VehicleVariantEditSaveViewModel viewModel)
If an error occurs during model binding in the POST action, I understand I can RedirectToAction back to the GET action and preserve the ModelState validation errors by copying it to TempData and retrieving it after the redirect in the GET action.
if (TempData["ViewData"] != null)
{
ViewData = (ViewDataDictionary)TempData["ViewData"];
}
How do I then convert that ViewData, which includes the previous invalid ModelState, into a new model to send to the view so the user sees their invalid input with validation warnings? Oddly enough if I pass in a new instance of my ViewModel retrieved from the database (with the original valid data) to the View() this is ignored and the (invalid) data in the ViewData is displayed!
Thanks
I had a similar problem and decided to use the following pattern:
public ActionResult PersonalRecord(Guid id)
{
if (TempData["Model"] == null)
{
var personalRecord = _context.PersonalRecords.Single(p => p.UserId == id);
var model = personalRecord.ToPersonalRecordModel();
return View(model);
}
else
{
ViewData = (ViewDataDictionary) TempData["ViewData"];
return View(TempData["Model"]);
}
}
[HttpPost]
public ActionResult PersonalRecord(PersonalRecordModel model)
{
try
{
if (ModelState.IsValid)
{
var personalRecord = _context.PersonalRecords.Single(u => u.UserId == model.UserId);
personalRecord.Email = model.Email;
personalRecord.DOB = model.DOB;
personalRecord.PrimaryPhone = model.PrimaryPhone;
_context.Update(personalRecord);
_context.SaveChanges();
return RedirectToAction("PersonalRecord");
}
}
catch (DbEntityValidationException ex)
{
var errors = ex.EntityValidationErrors.First();
foreach (var propertyError in errors.ValidationErrors)
{
ModelState.AddModelError(propertyError.PropertyName, propertyError.ErrorMessage);
}
}
TempData["Model"] = model;
TempData["ViewData"] = ViewData;
return RedirectToAction("PersonalRecord", new { id = model.UserId });
}
Hope this helps.
I noticed that the Model is included in ViewData so you don't need to pass it in addition to the ViewData, what I don't understand is how you get at it to then return it to the view.
public ViewResult Edit(int id)
{
// Check if we have ViewData in the session from a previous attempt which failed validation
if (TempData["ViewData"] != null)
{
ViewData = (ViewDataDictionary)TempData["ViewData"];
}
VehicleVariantEditViewModel viewModel = new VehicleVariantControllerViewModelBuilder()
.BuildForEdit(id);
return View(viewModel);
}
The above works but obviously it's making an unnecessary call to the database to build a new Model (which gets automagically overwritten with the invalid values from the Model in the passed ViewData)
Confusing.

Resources