Redirecting to the correct page after submitting a form in ASP.NET MVC - asp.net

I have the same
#Html.ActionLink("SUSPEND", "Suspend", "Serials", new { id = s.serial, orderId = s.Order.orderID }, null)
on two different pages.
Let's say I can click on it from this page:
http://localhost:55058/Customers/Details/4106
and from this page:
http://localhost:55058/Orders/Details/102091
The link takes me to a form associated to two standard Controller actions, GET:
public ActionResult Suspend(string id, string orderId)
{
Serial serial = context.Serials.Single(x => x.serialID == id);
ViewBag.orderId = orderId;
return View(serial);
}
and POST:
[HttpPost]
public ActionResult Suspend(Serial serial, string orderId)
{
if (ModelState.IsValid)
{
serial.suspended = true;
serial.suspensionDate = DateTime.Now;
context.Entry(serial).State = EntityState.Modified;
context.SaveChanges();
ViewBag.orderId = orderId;
return View(context.Serials.Single(x => x.serialID == serial.serialID));
}
}
How do I Redirect() to the page where I first clicked the link, once I submitted the form? Possibly, in an elegant way...
Thanks.

Related

Cannot post update to database. not all code paths return a value

[HttpPost]
public ActionResult UpdateDetail(User user)
{
bool Status = false;
string message = "";
// Model Validation
if (ModelState.IsValid)
{
using (UsersDatabaseEntities ude = new UsersDatabaseEntities())
{
var v = ude.Users.Where(a => a.Email == User.Identity.Name).FirstOrDefault();
user = v;
ude.Entry(User).State = EntityState.Modified;
ude.SaveChanges();
}
return View(user);
}
}
I keep on getting an error while saving data to the database.
UpdateDetail worked while retrieving message, but i keep getting error when saving.
Your issue is if your ModelState.IsValid == false, then you are not returning anything. I put a comment in code below where it is.
Depending on what your logic needs to do, would determine what needs to be returned if IsValid == false
public ActionResult UpdateDetail(User user)
{
bool Status = false;
string message = "";
// Model Validation
if (ModelState.IsValid)
{
using (UsersDatabaseEntities ude = new UsersDatabaseEntities())
{
var v = ude.Users.Where(a => a.Email == User.Identity.Name).FirstOrDefault();
user = v;
ude.Entry(User).State = EntityState.Modified;
ude.SaveChanges();
}
// this is your issue, this needs to be outisde the if statement, or you have to do an else and return null (or whatever you need to based off your logic)
return View(user);
}
}
Keep return statement outside of If statement. this would fix your error.If model is valid model updated with user details from database will be pushed to View. other wise same user model will be pushed to the view.
[HttpPost]
public ActionResult UpdateDetail(User user)
{
bool Status = false;
string message = "";
// Model Validation
if (ModelState.IsValid)
{
using (UsersDatabaseEntities ude = new UsersDatabaseEntities())
{
var v = ude.Users.Where(a => a.Email == User.Identity.Name).FirstOrDefault();
user = v;
ude.Entry(User).State = EntityState.Modified;
ude.SaveChanges();
}
}
return View(user);
}

Maintain DropdownList Selected value in mvc

I have a DropDown and on selcted indexchanged it forcefully postback and Binds a table,but after postback it didn't maintain the state.
my view is
#Html.DropDownListFor(m=>m.fkSubMenuID, (IEnumerable<SelectListItem>)ViewBag.list,"Select"
,new { id = "ddlSubMenu",onchange="SelectedIndexChanged()" })
and my controller is
public ActionResult ChildMenuOfSubMenu()
{
if (Session["DDlId"] == null || Convert.ToInt32(Session["DDlId"]) == 0)
{
UlrikenEntities dc = new UlrikenEntities();
var query = (from m in dc.ulriken_tblChildMenu
join sb in dc.ulriken_tblSubMenu on m.fkSubMenuID equals sb.pkSubMenuID
where m.Status == true && sb.fkMainMenuID == 1
select m).ToList();
Ulriken.Models.ChildMenu ObjHomeEvents = new Models.ChildMenu();
ObjHomeEvents.FormDetails = query;
FillDeptName();
Session["DDlId"] = null;
return View(ObjHomeEvents);
}
else
{
Int64 id = Convert.ToInt64(Session["DDlId"]);
UlrikenEntities dc = new UlrikenEntities();
var query = (from m in dc.ulriken_tblChildMenu
join sb in dc.ulriken_tblSubMenu on m.fkSubMenuID equals sb.pkSubMenuID
where m.Status == true && m.fkSubMenuID == id && sb.fkMainMenuID==1
select m).ToList();
Ulriken.Models.ChildMenu ObjHomeEvents = new Models.ChildMenu();
ObjHomeEvents.FormDetails = query;
FillDeptName();
//string ddlValue= ViewData.TemplateInfo.GetFullHtmlFieldId("ddlSubMenu");
Session["DDlId"] = null;
return View(ObjHomeEvents);
}
//return View();
}
and my javascript function is :
function SelectedIndexChanged() {
document.demoForm.submit();
}
Somebody guide me where am i doing wrong
Your controller action has no parameters... You need at least one parameter in the controller action to retrieve the value selected by the user.
public ActionResult ChildMenuOfSubMenu(int fkSubMenuID)
{
// ....
}
Probably will be better to have a method to show the view when the request is an HTTP GET and another one to handle the form submit (HTTP POST):
public ActionResult ChildMenuOfSubMenu()
{
// This method gets called in a HTTP GET
}
[HttpPost]
public ActionResult ChildMenuOfSubMenu(int fkSubMenuID)
{
// This one gets called when user performs the submit to the form
}

Save data instead of adding to database

I'm trying to edit an article in my asp.net mvc project. This is what I do when I create a project:
public ActionResult Create(ArticleViewModel model)
{
if (ModelState.IsValid)
{
try
{
// Get the userID who created the article
User usr = userrepo.FindByUsername(User.Identity.Name);
model.UsernameID = usr.user_id;
repository.AddArticle(model.Title, model.Description, model.ArticleBody);
}
catch (ArgumentException ae)
{
ModelState.AddModelError("", ae.Message);
}
return RedirectToAction("Index");
}
return View(model);
}
In my repository:
public void AddArticle(string Title, string Description, string ArticleBody)
{
item Item = new item()
{
item_title = Title,
item_description = Description,
article_body = ArticleBody,
item_createddate = DateTime.Now,
item_approved = false,
user_id = 1,
district_id = 2,
link = "",
type = GetType("Article")
};
try
{
AddItem(Item);
}
catch (ArgumentException ae)
{
throw ae;
}
catch (Exception)
{
throw new ArgumentException("The authentication provider returned an error. Please verify your entry and try again. " +
"If the problem persists, please contact your system administrator.");
}
Save();
// Immediately persist the User data
}
public void AddItem(item item)
{
entities.items.Add(item);
}
But now I want to edit an article, this is what I have till now:
public ActionResult Edit(int id)
{
var model = repository.GetArticleDetails(id);
return View(model.ToList());
}
[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult Edit(ArticleViewModel model)
{
if (ModelState.IsValid)
{
// Attempt to register the User
try
{
item Item = repository.GetArticleDetailsByTitle(model.Title);
Item.item_title = model.Title;
Item.item_description = model.Description;
Item.article_body = model.ArticleBody.
// HERE I NEED TO SAVE THE NEW DATA
return RedirectToAction("Index", "Home");
}
catch (ArgumentException ae)
{
ModelState.AddModelError("", ae.Message);
}
}
// If we got this far, something failed, redisplay form
return View(model);
}
As you can see I check the adjusted text and drop it in "Item". But how can I save this in my database? (the function in my repository)
I think your save() method had entityobject.SaveChanches()
So you want to call that save() method in here
try
{
item Item = repository.GetArticleDetailsByTitle(model.Title);
Item.item_title = model.Title;
Item.item_description = model.Description;
Item.article_body = model.ArticleBody.
**Save();**
return RedirectToAction("Index", "Home");
}
should be need to only Save() method, could not need to AddItem() method .
I'm afraid you'll need to get article again from database, update it and save changes. Entity framework automatically tracks changes to entites so in your repository should be:
public void EditArticle(Item article)
{
var dbArticle = entities.items.FirstOrDefault(x => x.Id == article.Id);
dbArticle.item_title = article.item_title;
//and so on
//this is what you call at the end
entities.SaveChanges();
}

Pass a value from controller to view

I have a problem in passing a value from controller to view
In controller, In the edit method
public ActionResult Edit( FormCollection form)
{
var id = Int32.Parse(form["CustomerServiceMappingID"]);
var datacontext = new ServicesDataContext();
var serviceToUpdate = datacontext.Mapings.First(m => m.CustomerServiceMappingID == id);
TryUpdateModel(serviceToUpdate, new string[] { "CustomerID", "ServiceID", "Status" }, form.ToValueProvider());
if (ModelState.IsValid)
{
try
{
var qw = (from m in datacontext.Mapings
where id == m.CustomerServiceMappingID
select m.CustomerID).First();
ViewData["CustomerID"] = qw;
datacontext.SubmitChanges();
//return Redirect("/Customerservice/Index/qw");
return RedirectToAction("Index", new { id = qw });
}
catch{
}
}
return View(serviceToUpdate);
}
Now in edit's view , I used this
#Html.Encode(ViewData["CustomerID"])
This is my Index method
public ActionResult Index(int id)
{
var dc = new ServicesDataContext();
var query = (from m in dc.Mapings
where m.CustomerID == id
select m);
// var a = dc.Customers.First(m => m.CustomerId == id);
// ViewData.Model = a;
// return View();
return View(query);
}
But the customerID on the page turns to be null.. Can u let me know if this procedure is correct?
You don't need to requery the id. Just use the id directly:
if (ModelState.IsValid)
{
datacontext.SubmitChanges();
//return Redirect("/Customerservice/Index/qw");
return RedirectToAction("Index", new { id = id});
}
Since you are redirecting the ViewData["CustomerID"] will be lost.
However the id in your Index method should be valid.
If your Index View requires the ViewData["CustomerID"] set it in your Index action:
public ActionResult Index(int id)
{
ViewData["CustomerID"] = id;
//....
I'm a bit confused as to which view does not have access to ViewData["CustomerId"]. If it's the Index view, you should set ViewData["CustomerId"] = id there.

Part of ASP.NET MVC application data save not being applied

I am writing an MVC application, and I wanted to do some extra formatting so the phone numbers all are stored the same. To accomplish this I made a simple external function to strip all non-numeric characters and return the formatted string:
public static string FormatPhone(string phone)
{
string[] temp = { "", "", "" };
phone = Regex.Replace(phone, "[^0-9]","");
temp[0] = phone.Substring(0, 3);
temp[1] = phone.Substring(3, 3);
temp[2] = phone.Substring(6);
return string.Format("({0}) {1}-{2}", temp[0], temp[1], temp[2]);
}
There is also regex in place in the model to make sure the entered phone number is a valid one:
[Required(ErrorMessage = "Phone Number is required.")]
[DisplayName("Phone Number:")]
[StringLength(16)]
[RegularExpression("^\\(?([0-9]{3})\\)?[-. ]?([0-9]{3})[-. ]?([0-9]{4})$",
ErrorMessage = "Please enter a valid phone number.")]
public object phone { get; set; }
This is what I did in the controller:
[HttpPost]
public ActionResult Edit(int id, FormCollection collection)
{
var customer = customerDB.Customers.Single(c => c.id == id);
try
{
customer.phone = HelperFunctions.FormatPhone(customer.phone);
UpdateModel(customer,"customer");
customerDB.SaveChanges();
return RedirectToAction("Index");
}
catch
{
var viewModel = new CustomerManagerViewModel
{
customer = customerDB.Customers.Single(c => c.id == id)
};
return View(viewModel);
}
}
When I step through this, the string updates then resets back to the format it was before being ran through the function. Also, any of the other fields update with no problem.
Any ideas? Thanks in advance.
Your UpdateModel call is overwriting the customer field. Try swapping these two lines of code:
try
{
UpdateModel(customer,"customer"); <--
customer.phone = HelperFunctions.FormatPhone(customer.phone); <--
customerDB.SaveChanges();
return RedirectToAction("Index");
}

Resources