asp.net mvc create a database record - asp.net

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

Related

The procedure does not work properly Entity Framework ASP.NET MVC 5 C#5

I have been facing this problem with assigning users to a proper role. The code looks just fine, but in reality half of the users gets a proper role, the other half stays without a role at all. Here is the method which does it:
public IdentityResult RefreshUserGroupRoles(long? userId)
{
if (userId == null) throw new ArgumentNullException(nameof(userId));
var user = _userManager.FindById(userId.Value);
if(user == null)
{
throw new ArgumentNullException(nameof(userId));
}
// Remove user from previous roles:
var oldUserRoles = _userManager.GetRoles(userId.Value);
if (oldUserRoles.Count > 0)
{
_userManager.RemoveFromRoles(userId.Value, oldUserRoles.ToArray());
}
// Find the roles this user is entitled to from group membership:
var newGroupRoles = this.GetUserGroupRoles(userId.Value);
// Get the damn role names:
var allRoles = _roleManager.Roles.ToList();
var addTheseRoles = allRoles.Where(r => newGroupRoles.Any(gr => gr.AppRoleId == r.Id));
var roleNames = addTheseRoles.Select(n => n.Name).ToArray();
//_db.Database.CurrentTransaction.Commit();
// Add the user to the proper roles
var transaction = _db.Database.BeginTransaction();
IdentityResult result;
try
{
result = _userManager.AddToRoles(userId.Value, roleNames);
transaction.Commit();
_db.DbContextTransactionAu.Commit(); //This is for Audit
}
catch (Exception)
{
transaction.Rollback();
throw;
}
_db.DbContextTransactionAuDispose?.Dispose();
return result;
}
public IEnumerable<AppGroupRole> GetUserGroupRoles(long userId)
{
var userGroups = this.GetUserGroups(userId).ToList();
if (userGroups.Count == 0) return new Collection<AppGroupRole>().AsEnumerable();
var userGroupRoles = new List<AppGroupRole>();
foreach(var group in userGroups)
{
userGroupRoles.AddRange(group.AppRoles.ToArray());
}
return userGroupRoles;
}
Any idea what could be wrong?

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

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