Updating string in ASP.NET and MVC LINQ to SQL
I have a simple four-column row:
{ [Primary Key Int]RowID, [text]Title, [text]Text, [datetime]Date }
I would like to allow the user to edit this line on a simple page that has a form with both Title and Text fields.
There is a hidden field to store the RowID.
When a user submits this form to my controller action, I want it to update the title and text of the row and keep the date the same. I don't want to explicitly list a hidden date field on the form page.
Here is my action:
[AcceptVerbs(HttpVerb.Post)]
public ActionResult EditRow(Row myRow)
{
RowRepository.SaveRow(myRow)
return View("Success");
}
RowRepository:
public void SaveRow(Row myRow)
{
db.MyRows.Attach(myRow);
db.Refresh(RefreshMode.KeepCurrentValues, myRow);
db.SubmitChanges();
}
This should not contain a "Date" value already on the line and tries to insert a value that throws a time-sensitive exception.
How can I just say to keep the old values? I've tried doing RefreshMode.KeepChanges
and nothing.
source to share
Ok, I set it to NULL and it overwrites the database as null. I guess this is not possible to do, since technically null is a valid value for the column, and if I pass a function object, the empty values ββmust contain something or be null.
So I would have to explicitly specify the database value for this column
thank
source to share
Try
[AcceptVerbs(HttpVerb.Post)]
public ActionResult EditRow([Bind(Exclude="Date")] Row myRow) {
RowRepository.SaveRow(myRow)
return View("Success");
}
Update
Try this approach if your page doesn't have a Date field
[AcceptVerbs(HttpVerb.Post)]
public ActionResult EditRow(int RowID) {
Row myRow = RowRepository.GetRow(RowID);
UpdateModel(myRow);
RowRepository.Save();
return View("Success");
}
In your repository
public void Save() {
db.SubmitChanges();
}
This will save the changes made to 'myRow'
source to share
You will have a method added in the partial class / override the generated code.
The class table implements "INotifyPropertyChanging | ed", which is used to keep track of which column has changed.
You can hack it and reset the "this.PropertyChanged" value.
But what I am doing at work is the silly READ-APPLY-WRITE approach (and I am using WebForm).
public void SaveRow(Row myRow)
{
var obj=db.MyRows.Where(c=>c.id==myRow.id).First();
obj.a=myRow.a;
obj.b=myRow.b;
db.SubmitChanges();
}
You can make it a little easier.
public void SaveRow(Row myRow)
{
db.MyRows.Attach(new Row(){
Id=myRow.Id,
Title=myRow.Title,
Text=myRow.Text,
});
db.SubmitChanges();
}
PS. I am new to LINQ to SQL. Please let me know if there is a smarter way to do this.
source to share