问题
Any ideas why this doesn't update but doesn't throw an error?
public ActionResult Edit(int id, [Bind(Exclude = "deptid")]FormCollection collection)
{
var department = _repository.ListOne(id); //Grabs record from linq to sql
try
{
UpdateModel(department);
_entities.SubmitChanges();
// TODO: Add update logic here
return RedirectToAction("Index");
}
catch
{
return View(department);
}
}
回答1:
Sometimes what may happen is an error is thrown somewhere inside of the MVC assembly which is not handled nicely, and which does not get copied into your model state as expected. Then, when you try to display in your view the Html.ValidationSummary
, it doesn't show you the error, which can be very confusing. One example that can crash this model binding process I've written about here. Usually, after you figure out why this is happening, you can make the corrections to your code and not worry about it anymore.
I have the following code that I use to inspect during debugging, to let me hover over it at a breakpoint and see what is really going on:
public static IDictionary<string, string> GetModelStateErrors(this ViewDataDictionary viewDataDictionary)
{
Dictionary<string, string> dict = new Dictionary<string, string>();
foreach (var modelStateKey in viewDataDictionary.ModelState.Keys)
{
var modelStateValue = viewDataDictionary.ModelState[modelStateKey];
foreach (var error in modelStateValue.Errors)
{
var errorMessage = error.ErrorMessage;
var exception = error.Exception;
if (!String.IsNullOrEmpty(errorMessage))
{
dict.Add(modelStateKey, "Egads! A Model Error Message! " + errorMessage);
}
if (exception != null)
{
dict.Add(modelStateKey, "Egads! A Model Error Exception! " + exception.ToString());
}
}
}
return dict;
}
Then, I can insert this after I try to UpdateModel, and set a breakpoint on it:
var x = ViewData.GetModelStateErrors();
Put this right after your call to UpdateModel
. Hovering over the x
will show you any unhandled exceptions in the model-binding process, if that is what is really the problem here.
Good luck!
回答2:
While using Linq to Sql for Model Classes, If you are updating against a table that doesn't have a Primary Key, then calling updateModel()
method will not update the data and won't give any Error Either.
The solution in such a case is to use ExecuteCommand
or ExecuteQuery
methods with the Object of your DataContext Class.
ex:
MyDataContext db= new MyDataContext();
string name="test";
int roll=123;
string UpdateStatement="Update table xyz set name='+ name+"' where roll="+ roll;
db.ExecuteCommand(UpdateStatement);
来源:https://stackoverflow.com/questions/1461283/asp-net-mvc-updatemodel-not-updating-but-not-throwing-error