ASP .net Dropdown list not saving the selected value to database - asp.net

In the following code i want to save the value selected by user from drop downlist into database. but whatever value is selected by user, first value of dropdown lsit is saved to database
View
<% =Html.DropDownList("lstUsertype", (SelectList)ViewData["UserTypeID"])%>
Controller
public ActionResult CreateUser()
{
UmUser _UmUser = new UmUser();
UMRepository _UMRepository = new UMRepository();
EvoLetDataContext db = new EvoLetDataContext();
ViewData["UserTypeID"] = new SelectList(_UMRepository.FillUserTypes(), "UserTypeID", "UserType",2);
return View(_UmUser);
}
[AcceptVerbs(HttpVerbs.Post)]
public ActionResult CreateUser(UmUser _umUser)
{
//try
//{
if (ModelState.IsValid)
{
//try
//{
UserRepository _UserRepository = new UserRepository();
_UserRepository.Add(_umUser);
_UserRepository.Save();
return RedirectToAction("Details", new { id = _umUser.UserID });
/*}
catch
{
ModelState.AddModelErrors(_umUser.GetRuleViolations());
}*/
}
return View();
//}
/*catch
{
return View();
}*/
}

This is how I'm doing it successfully:
<%= Html.DropDownListFor(model => model.Value, new SelectList(Values, "Key", "Value", Model.Value), "[select]")%>
Where Values is of type IDictionary and Value is of type Guid
Hope this helps!

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);
}

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

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.

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();
}

ASP.NET MVC create a new database record

I've been learning asp.net mvc 3. So, basically I'm trying to create a new record in database. However, I'm trying to keep a particular record predefined
public ActionResult Create()
{
var dc = new ServicesDataContext();
var model = new Maping();
var query = (from m in dc.Customers
where m.CustomerId == model.CustomerID
select m.CustomerId);
ViewData["CustomerID"] = query.First();
return View(model);
}
//
// POST: /Customerservice/Create
[AcceptVerbs(HttpVerbs.Post)]
public ActionResult Create([Bind(Exclude="CustomerServiceMappingID")] Maping serviceToCreate, FormCollection form)
{
if (!ModelState.IsValid)
return View();
var dc = new ServicesDataContext();
dc.Mapings.InsertOnSubmit(serviceToCreate);
try
{
dc.SubmitChanges();
}
catch (Exception e)
{
}
try
{
var id = Int32.Parse(form["CustomerID"]);
ViewData["CustomerID"] = id;
return RedirectToAction("Index", new { id = id });
}
catch
{
return RedirectToAction("INDEX", "Home");
}
}
So this is what I did. So, the case is that id value in second action method is what i needed. However the second method gets redirectd to index so viewdata value is lost.And the thing i did in the first crate method is wrong because no value is assigned. So, can u please help me with this problem.
Use TempData, not ViewData - it will be valid until it is read again. Also why are you adding it into viewdata when it is being passed as a parameter in the RedirectToAction?

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.

Resources