So I'm trying to add a new row of information into the database table I'm using and currently it sometimes adds from 2-5-7 rows of the same information into to the database but with different Id's.
I have tried to debug through the process and I don't understand why the ActionResult runs several times and adds the same information up to 7(!) times.
When I click the add button it starts to load the the next page and the values are added to the database. The problem is that about 5-6 seconds later after clicking the add button it goes back to the controller again and do the same process again witch result in a random number of 2-5-7 rows added with the same values but different id's.
I am using a simple View with editor-fields and a dropdown list to select countries and it is posted to the a ActionResult that adds the values into the database.
The ActionResult look like this:
[HttpPost]
public ActionResult AddNewsdesk(AddNewsdeskViewModel addNewsdesk)
{
if (ModelState.IsValid)
{
var newsdesk = Mapper.Map<AddNewsdeskViewModel, Newsdesk>(addNewsdesk);
newsdesk.Country = _databaseContext.Countries.Single(c => c.Name.Equals(addNewsdesk.Country));
newsdesk.Id = new Guid();
_databaseContext.Add(newsdesk);
_databaseContext.SaveChanges();
return RedirectToAction("Index", "Newsdesk");
}
return RedirectToAction("Index", "Home");
}
Related
I just want to know the logic of this. I am not posting any code because I don't know what is the logic behind this so please pardon. I have a page call dynamicPage. This page is connected with database & everytime details of particular things gets fetched according to users selected. Now I want to track How many time particular thing is visited.
e.g.
Hospital1
Hospital2
Hospital3
If user clicks on Hospital2 then it's count get increased by one & so on..
I made this site http://www.brandstik.in/Music here many products are listed. Now I want to see how many times particular products is viewed.
You need something between clicking on the product link and loading the detail page. There are lots of ways to do that. One of the easiest ones is to have a method between you clicked on the link and loading the detail page. So the simplest solution that I can suggest is to have an action (if it is MVC) or a simple method on detail page, increase the count and then redirect to the original one. So lets say your code is in MVC and you have a method like this on dynamic page:
#Html.ActionLink("#item.productName", "Index", "Products", new {id = "#item.id"}))
and you have this code in your products controller:
public class ProductsController:Controller
{
Public ActionResult Index(int Id)
{
...some code to load and return the productDetails
}
}
Then you need to add a method to add to the count and then redirects to the original method. so your controller will be like this:
public class ProductsController:Controller
{
Public ActionResult Index(int Id)
{
//some code to load and return the productDetails
}
public ActionResult IncreaseProductCount(int Id)
{
//increase the count
return RedirectToAction("Index",new{Id=Id});
}
}
And then on the dynamic page view change your code to call the new method instead:
#Html.ActionLink("#item.productName", "IncreaseProductCount", "Products", new {id = "#item.id"}))
Here is the problem. User can come to set and enter in text in an upper and lower text box. After they have done so that text will then be stored in a datatable which will hold a Guid Id, a Title string, and a Body string.
How do I arrange it so that a if the page reloads (meaning the data gets sent to the data base) that if the user changes come text and hits submit again that the table will change accordingly and not make a new row.
I am thinking I will need an if statement to pull this off but I am not sure what to put within the statement. There is the code I have thus far in a .net mvc controller
[HttpPost]
public ActionResult ActName(ModelNameModel item)
{
if( ModelState.IsValid)
{
using (DB.DatabaseName db = new DB.DatabaseName())
{
DB.Model newRecord = new DB.Model();
newRecord.Title = item.Title;
newRecord.Body = item.Body;
newRecord.Id = Guid.NewGuid();
db.Models.Add(newRecord);
db.SaveChanges();
}
}
return View(item);
}
What other if statement can I use to verify the Guid Matches? Thank you!
I have a serial number generation method on MVC 4
When i select a Product ID from the DDL and press create it, it generates a serial number no problem to the Index page
However i would like to have the Serial number presented to the user during the creation process, so as soon as they select a value from the DDL, the serial number will be generated and displayed in a read only box.
Below is my snippet that does the serial generator
//
// POST: /Item/Create
[HttpPost]
public ActionResult Create(Item item)
{
if (ModelState.IsValid)
{
string SerialNumber = string.Format("SN/{0}/{1}", DateTime.Now.Year, item.ProductID);
item.SerialNumber = SerialNumber;
db.Items.Add(item);
db.SaveChanges();
return RedirectToAction("Index");
}
ViewBag.ProductID = new SelectList(db.Products, "ProductID", "ProductID", item.ProductID);
return View(item);
}
I have very little experience with jquery so it would be great to get pointers or help on how to accomplish this idea. If there is even a better way than jquery please let me know :)
Any info requests i will be happy to supply
Thanks
this will give you can exact idea binaryintellect.net/articles/… – #Frebin Francis (credit goes to Frebin)
I'm wanting to capture the old values within a model so I can compare with the new values after submission, and create audit logs of changes a user makes.
My guess is doing it with hidden input boxes with duplicated old value properties would be one way. But wondering if there are any other good alternatives?
Thanks
In the save method, just go and get the original object from the database before saving the changes, then you have your old and new values to compare against? :)
This sounds like standard auditing. You should not worry about what has changed just capture EVERYTHING and who made the change. Unless there is some sort of real time reporting that needs to be done.
Possible auditing implementations:
CQRS, in a nutshell it tracks every change to a given object. The downside is it's an architecture that is more involved to implement.
The Rolling ledger. Each insert is a new row in the database. The most current row is used for display purposes, but with each update, a new row is inserted into the database.
Yet another approach is to save it off into an audit table.
All get the job done.
You could also store the original model in the view bag and do something like this...
// In the controller
public ActionResult DoStuff()
{
// get your model
ViewBag.OriginalModel = YourModel;
return View(YourModel);
}
// In the View
<input type="hidden" name="originalModel" value="#Html.Raw(Json.Encode(ViewBag.OriginalModel));" />
// In the controller's post...
[HttpPost]
public ActionResult DoStuff(YourModel yourModel, string originalModel)
{
// yourModel will be the posted data.
JavaScriptSerializer JSS = new JavaScriptSerializer();
YourModel origModel = JSS.Deserialize<YourModel>(originalModel);
}
I didn't get a chance to test this, just a theory :)
Exactly what mattytommo says is the preferred method all around
Instantiate new view model for creating a new entity
public ActionResult Edit(int id) {
var entity = new Entity(id); // have a constructor in your entity that will populate itself and return the instance of what is in the db
// map entity to ViewModel using whatever means you use
var model = new YourViewModel();
return View(model);
}
Post changes back
[HttpPost]
public ActionResult Edit(YourViewModel model) {
if (ModelState.IsValid) {
var entity = new YourEntity(model.ID); // re-get from db
// make your comparison here
if(model.LastUserID != entity.LastUserID // do whatever
... etc...
}
return View(model);
}
I am working through sample MVC Nerdinner tutorial and using it on the AdventureWorks database. I have created an Edit action in the CategoryController to edit Product Category in AdventureWorks. The only updateable field in this table is the Name (the other fields - ID, RowGUID and UpdateDate are autogenerated). So my edit form View has only 1 field for the Name (of Product Category). My "Save" action for the edit is below: -
[AcceptVerbs(HttpVerbs.Post)]
public ActionResult Edit(int id, FormCollection collection){
ProductCategory p = awRepository.GetProductCategory(id);
try
{
//UpdateModel(p);
p.Name = Request.Form["Name"];
awRepository.Save();
return RedirectToAction("Details", new { id = p.ProductCategoryID });
}
catch
{
foreach (var err in p.GetRuleViolations())
{
ModelState.AddModelError(err.PropertyName, err.ErrorMessage);
}
return View(p);
}
}
If I use the code as above, everything works as long as the Name I enter is valid (thus there is no exception). If I introduce an error (which is raised by GetRuleViolations if the Name is blank or for testing purposes is a particular "Test" string) I get a NullReferenceException (Object reference not set to an instance of an object) on this line in the View (Category/Edit.aspx) when the Edit View is redrawn (to show the user the error and allow him to correct)
<%= Html.TextBox("Name") %>
If I update my ProductCategory using UpdateModel(p) instead of using the Request.Form variable, everything works fine; Valid data is saved and invalid data redraws the view showing the error message.
My question is: what is the difference between UpdateModel and manual updating my variable by reading the values from Request.Form collection? The Nerdinner tutorial seems to suggest that both are equivalent. So I am surprised that one works smoothly and the other raises an exception.
Sounds like this:
http://forums.asp.net/p/1396019/3006051.aspx
So, for every error you add with
ModelState.AddModelError() and call
the View again, MVC Framework will try
to find an AttemptedValue for every
error it finds. Because you didn't add
them, MVC will throw an exception.
Normally you don't need to add these
values: AttemptedValues are
automaticaly populated when you use
DefaultBinding (by calling
UpdateModel() or by passing the object
to bind as an Action Method paramter:
public ActionResult
Create(FormCollection Form,
YourObjectType yourObject).
Looks like the following is done automatically by UpdateModel, but not done manually by yourself?
if (Form["Name"].Trim().Length == 0)
{
ModelState.AddModelError("Name", "Name is required");
//You missed off SetModelValue?
ModelState.SetModelValue("Name", Form.ToValueProvider()["Name"]);
}