ASP.NET MVC Updatemodel does not update, but does not throw an error

Any ideas why this is not updating but not throwing errors?

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
source share
2 answers

Sometimes it happens that an error occurs somewhere inside the MVC assembly, which is not handled beautifully and which is not copied to your model state, as expected. Then, when you try to display in your view Html.ValidationSummary, it does not show you an error, which can be very confusing. One example that may cause the model binding process to fail, which I wrote about here here . As a rule, after you find out why this happens, you can make corrections to your code and no longer worry about it.

, , , :

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

, Model, :

var x = ViewData.GetModelStateErrors();

UpdateModel. x , .

!

+5

Linq to Sql , , , updateModel() . ExecuteCommand ExecuteQuery DataContext.

:

MyDataContext db= new MyDataContext();
string name="test";
int roll=123;

string UpdateStatement="Update table xyz set name='+ name+"' where roll="+ roll;
db.ExecuteCommand(UpdateStatement);
+1

Source: https://habr.com/ru/post/1757920/


All Articles