I have an Edit form, and have a problem when saving the result.
View:
<div class="editor-label">
@Html.LabelFor(model => model.LoginModel.Uzytkownik)
</div>
<div class="editor-field">
@Html.EditorFor(model => model.LoginModel.Uzytkownik)
@Html.ValidationMessageFor(model => model.LoginModel.Uzytkownik)
</div>
Model:
namespace Restauracja.Models
{
public class pracownikModel
{
public LoginModel LoginModel { get; set; }
public uzytkownikModel uzytkownikModle { get; set; }
public pracownikModel() {
LoginModel = new LoginModel();
uzytkownikModle = new uzytkownikModel();
}
}
public class LoginModel
{
[Required]
public string Uzytkownik { get; set; }
[Required]
public string Haslo { get; set; }
public string Konto { get; set; }
}
public class uzytkownikModel
{
[Required]
public string imie { get; set; }
....
}
}
Controller:
[HttpGet]
public ActionResult Edit(int LoginID)
{
pracownikModel prac = new pracownikModel();
var pr = (from p in baza.Logowanies where LoginID == p.LoginID select p).First();
prac.LoginModel.Uzytkownik = pr.Login;
return View(prac);
}
[HttpPost]
public ActionResult Edit(int LoginID, pracownikModel prac)
{
var xxx = (from z in baza.Logowanies where LoginID == z.LoginID select z).Single();
xxx.Login = prac.LoginModel.Uzytkownik;
baza.SubmitChanges();
return RedirectToAction("Index", "Foo");
}
Function with [HttpGet] is working properly, showing result from database. The problem is with second function… prac is null… So this cannot work because I can’t write null to the database. I don’t know how to solve this problem.
I would recommend you to use only standard ASCII letters and numbers when naming your variables and classes. The default model binder uses those names when trying to bind the properties from the POST request. Also since those property names are used as name and id attribute of the input elements in the HTML you end up with invalid HTML according to the specification which states:
So you should not use extended ASCII or unicode symbols such as
łandż. Replace them with their corresponding ASCII character and the default model binder will be able to correct fetch the values.UPDATE:
After looking at the sample code you sent me in your Edit view you currently have 3 forms:
The first form is the only one that contains input fields for your model. So it is by submitting only the first form that you can expect to populate some of the properties of your model in the POST action. Unfortunately this first form doesn’t have a submit button so you cannot submit it. The second and third form contain submit buttons but they do not contain any input field so submitting them will leave the model totally blank.
So what you need here is to move the Save submit button inside the first form:
or since the Cancel submit button posts currently to a controller action tat performs a redirect you could simply replace it with an anchor which will redirect: