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.
Related
[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);
}
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
}
i already try to store my viewmodel to session.
i store my database to viewmodel, and i want to save viewmodel value to session
i try to use
List<GetUserNameViewModel> getName = _accountService.GetLoginName(UserID)
Session["GetName"] = getName;
but value is
System.Collections.Generic.List`1[XNet.Repository.Model.GetUserNameViewModel], not Username...
how can i save my viewmodel value to session??
this my service
public List<GetUserNameViewModel> GetLoginName(int UserID)
{
List<User> user = (from d in _UserRepository.All()
where d.UserID == UserID
select d).ToList();
List<GetUserNameViewModel> GetName = new List<GetUserNameViewModel>();
foreach (User users in user)
{
GetName.Add(new GetUserNameViewModel
{
UserName = users.UserName
});
}
return GetName;
}
my controller
public ActionResult Index()
{
int UserID = Convert.ToInt32(User.Identity.Name);
List<GetUserNameViewModel> getName = _accountService.GetLoginName(UserID);
Session["GetName"] = getName;
return View();
}
In the View (Razor), you've to cast the object in order to traverse the List<T> if that list has two or more GetUserNameViewModel object references or just call FirstOrDefault() method to read the first or default element from the List<T>,
#{
List<GetUserNameViewModel> getNames = Session["GetName"] as List<GetUserNameViewModel>;
for(var name in getNames){
//statements
}
//Or
GetUserNameViewModel name = getNames.FirstOrDefault();
}
And in other case, change the GetLoginName method. I think GetLoginName method should returns an object not a List<T>.
public GetUserNameViewModel GetLoginName(int UserID)
{
User user = (from d in _UserRepository.All()
where d.UserID == UserID
select d).FirstOrDefault();
if(user==null)
return null;
return new GetUserNameViewModel() { UserName = user.UserName };
}
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?
So, I've been trying to create a record.however I created it successfully but the problem is that I may need the ID that has been auto incremented.
[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)
{
}
after this, I tried to do this which has not been working
var id = Int32.Parse(form["CustomerServiceMappingID"]);
var qw = (from m in dc.Mapings
where id == m.CustomerServiceMappingID
select m.CustomerID).First();
// var id = Int32.Parse(form["CustomerID"]);
return RedirectToAction("Index", new { id = qw });
Now I need to send Customer ID as a parameter to Index.. SO, can u help me out..
Thanks,
I would rewrite as (dont exclude the ID from the parameter list - a particular reason this needs to be excluded?):
[HttpPost]
public ActionResult Create(Maping serviceToCreate)
{
if (!ModelState.IsValid)
{
return View();
}
var dc = new ServicesDataContext();
dc.Mapings.InsertOnSubmit(serviceToCreate);
dc.SubmitChanges();
//try to get the values from 'Maping' model if possible?
var qw = (from m in dc.Mapings
where m.CustomerServiceMappingID == serviceToCreate.CustomerServiceMappingId
select m.CustomerID).First();
return RedirectToAction("Index", new { id = qw });