1

I want to pass Data of a Form from view to Controller with ViewModel is that possible?? I am getting null while sending data. My Code is :

My ViewModel contain model class reference. The data which i want to pass is for two model i.e MasterSchoolInfo and MasterUserInfo, but on submitting the posted value in controller is showing bull. Any help on this will be very helpful. I am new to Asp.Net MVC.

If i am passing Models to the contoller, then that is working fine, but once i changed it to viewmodel it started posting null to controller.

I idea behind changing from Model to ViewModel was because i want to pass data for two different Models and use them in the controller.

ViewModel

namespace ABC.ViewModels
{
    public class UserInfoViewModel
    {
        public MasterSchoolInfo School { get; set; }
        public MasterTeacherInfo Teacher{ get; set; }
        public MasterStudentInfo Student { get; set; }
        public MasterParentInfo Parent { get; set; }
        public MasterUserInfo User { get; set; }
        public MasterUserRole Role { get; set; }

    }
}

Controller

[HttpPost]
public ContentResult CreateSchool(UserInfoViewModel _usrData)
{
    var content = string.Empty;
    if ((!String.IsNullOrEmpty(HttpContext.Session.GetString("UserEmail"))) && (!String.IsNullOrEmpty(HttpContext.Session.GetString("UserRole"))))
    {
        int UserId = Convert.ToInt32(HttpContext.Session.GetString("UserId"));
        string UserEmail = Convert.ToString(HttpContext.Session.GetString("UserEmail"));
        string UserRole = Convert.ToString(HttpContext.Session.GetString("UserRole"));
        byte[] salt = encryption.generatePasswordSalt("school");
        string password = encryption.generateHashedPassword("school", salt);
        if (UserRole == "Super Administrator")
        {
            _usrData.School.CreatedBy = UserEmail;
            _usrData.School.CreatedOn = DateTime.Now;
            _usrData.School.ApprovalStatus = true;
            _usrData.School.Status = true;
            MasterUserInfo userInfo = new MasterUserInfo();
            userInfo.RoleId = 4;
            userInfo.EmailId = _usrData.School.PrimaryEmailId;
            userInfo.Salt = Convert.ToBase64String(salt).ToString();
            userInfo.Password = password;
            userInfo.CreatedBy = UserEmail;
            userInfo.CreatedOn = DateTime.Now;
            userInfo.ApprovalStatus = true;
            userInfo.Status = true;
            //string[] str = schoolInfo.PrimaryEmailId.Split('.');
            //userInfo.Username = str[0].ToString();
            userInfo.Username = _usrData.User.Username.ToString();
            MasterSchoolInfo masterSchool = _context.Set<MasterSchoolInfo>().LastOrDefault();
            if (masterSchool != null)
            {
                var lastschoolcode = masterSchool.OpinschoolCode;                   
                var val = lastschoolcode.Substring(4, lastschoolcode.Length - 4);
                int r = Convert.ToInt32(val) + 1;
                string newusercode = "IESC000" + r;
                userInfo.UserCode = newusercode;
                _usrData.School.OpinschoolCode = newusercode;
            }
            else
            {
                string newusercode = "IESC000" + 1;
                userInfo.UserCode = newusercode;
                _usrData.School.OpinschoolCode = newusercode;
            }
            if (ModelState.IsValid)
            {

                _context.MasterUserInfo.Add(userInfo);
                _context.SaveChanges();

                MasterUserInfo masterUser = _context.Set<MasterUserInfo>().Last();
                _usrData.School.UserId = masterUser.Id;
                _context.MasterSchoolInfo.Add(_usrData.School);
                _context.SaveChanges();
                TempData["Message"] = "School Added Successfully!";
                content = "Success";
            }
            else
            {
                content = "Error";
            }
        }
        else
        {
            content = "Error";
        }
    }
    else
    {
        content = "Error";
    }
    return Content(content);
}
2
  • "If i am passing Models to the contoller, then that is working fine, but once i changed it to viewmodel it started posting null to controller" what you mean under Model and ViewModel o_O?. Commented Oct 4, 2017 at 12:40
  • Model means the data was passed directly using the model class for MasterSchoolInfo and that was working fine, but now when i changed it to pass via ViewModel, it posting null @SeM Commented Oct 4, 2017 at 12:52

1 Answer 1

2

for example if your Code is :

 public class MasterSchoolInfo 
 {
          public string name{get;set;}
 }

you should implement input in view:

<input type="text" name="school.name">
Sign up to request clarification or add additional context in comments.

2 Comments

Thanks @soroosh. This was the thing which i missed. I was using asp-for so i thought that would be sufficient. Thanks a lot Buddy
Normally you can use asp-for: <input asp-for="Model.School.Name" />.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.