How to fix Microsoft.CSharp.RuntimeBinder.RuntimeBinderException: Cannot perform runtime binding on a null reference in asp.net mvc?

匿名 (未验证) 提交于 2019-12-03 01:45:01

问题:

I get the following exception in my system.This system worked properly. But suddenly got and exception. I tried doing debugging. But I couldn't find the anything. This is about a profile picture upload. I did some removing of code and I got the error. But then I again add those codes but nothing happen. I tried some solutions in the internet but didn't work. I'm new to this work so please help me if you can. I tried removing some of the codes then I got an error saying invalid operation.
How can I fix this?
I tried to debug and find where the problem occurs, unfortunately I couldn't find where it is.But I guess the problem should be in these codes. These two codes created the exception

Code part 1

  •                     @{                         var imgUrl = @Url.Content("~/Content/profile/" + Model.SID + ".png") + "?time=" + DateTime.Now.ToString();                     }                     <img id="user_img" src="@imgUrl" height="50" width="50" style="margin-top:2px" />                 </li>             

    Code part 2

    @if (Model.SID != null)                             {                                 var imgUrl = @Url.Content("Content/profile/" + Model.SID + ".png") + "?time=" + DateTime.Now.ToString();                                 <div class="input-field col s12">                                     <div class="input-field col s12">                                         <img id="user_img" src="@imgUrl" height="1" width="1" />                                     </div>                                      <div class="mngimg">                                         @using (Html.BeginForm("UploadPhoto", "Profile", FormMethod.Post, new { enctype = "multipart/form-data" }))                                         {                                             <div class="input-field col s12">                                                 <input type="file" name="file" id="files" onchange="this.form.submit()" />                                             </div>                                         }                                     </div>                                 </div>                             } 

    @section Scripts {   <script>     $(document).ready(function () {              $.validator.setDefaults({                 errorClass: 'invalid',                 validClass: "valid",                 errorPlacement: function (error, element)                 {                     $(element)                         .closest("form")                         .find("label[for='" + element.attr("id") + "']")                         .attr('data-error', error.text());                 },                 submitHandler: function () {                      event.preventDefault();                     var SID = $("[name='SID']").val();                     var fName = $("[name='fname']").val();                     var lName = $("[name='lname']").val();                     var dob = $("[name='dob']").val();                     var email = $("[name='email']").val();                     var pw = $("[name='password']").val();                     var confirmPw = $("[name='confirmPassword']").val();                     var phone = $("[name='phone']").val();                     var address = $("[name='address']").val();                      var user = {                          SID: SID,                         FirstName: fName,                         LastName: lName,                         DOB: dob,                         email: email,                         Password: password,                         Phone: phone,                         Address: address                      }                      //console.log(SID + " " + email + " " + password);                      $.ajax({                         type: 'POST',                         url: 'saveChanges',                         contentType: 'application/json',                         data: JSON.stringify(user),                         dataType: 'Json',                         async: true,                         success: function (data) {                             if (data == true) {                                 Materialize.toast('Details Updated Successfully !!!', 4000, 'blue')                             }                         }                      });                  }              });              $.validator.addMethod("regx", function (value, element, regexpr) {                 return regexpr.test(value);             }, "must contain more than 8 characters & at least 1 Alphabet and 1 Number");              $("#form").validate({                 rules: {                     SID: {                         required: true,                         minlength: 10,                         maxlength: 10                     },                     fName: {                         required: true,                         minlength: 4,                         maxlength: 20                     },                     lName: {                         required: true,                         minlength: 4,                         maxlength: 20                     },                     dob: {                         required: true,                      },                     email: {                         required: true,                         email: true                     },                      Phone: {                         required: true,                         regx: /^\d{10}$/,                         minlength: 10,                         maxlength: 10                     },                  },                  messages: {                     fName: {                         required: true,                         minlength: "Should be minimum 4 characters",                         maxlength: "Should be maximum 20 characters",                      },                     lName: {                         required: true,                         minlength: "Should be minimum 4 characters",                         maxlength: "Should be maximum 20 characters"                     },                     Phone: {                         minlength: "Enter valid phone number",                         maxlength: "Enter valid phone number"                     }                  }             });          });       </script> }
    <form id="form" style="width:100%; height:auto; margin-left:1%; margin-top:1%" method="post">  	@*<div class="input-field col s12 "> 			<i class="material-icons prefix">account_circle</i> 			<input id="img" name="img" type="image" value="" readonly="readonly" style="margin-top:5%; margin-bottom:1%"> 			<label for="img">Profile Picture</label> 		</div>*@ 	<div class="input-field col s12 "> 		<i class="material-icons prefix">subtitles</i> 		<input id="SID" name="SID" type="text" value="@Model.SID" readonly="readonly"> 		<label for="SID">Student ID</label> 	</div> 	<div class="input-field col s12"> 		<i class="material-icons prefix">account_circle</i> 		<input id="fname" name="fname" type="text" class="validate" value="@Model.FirstName"> 		<label for="fname">First Name</label> 	</div> 	<div class="input-field col s12"> 		<i class="material-icons prefix">account_circle</i> 		<input id="lname" name="lname" type="text" class="validate" value="@Model.LastName"> 		<label for="lname">Last Name</label> 	</div> 	<div class="input-field col s12"> 		<i class="material-icons prefix">Address</i> 		<input id="address" name="address" type="text" class="validate" value="@Model.Address"> 		<label for="lname">Address</label> 	</div> 	<div class="input-field col s12"> 		<i class="material-icons prefix">phone</i> 		<input id="phone" name="phone" type="text" class="validate" value="@Model.Phone"> 		<label for="lname">Phone</label> 	</div> 	<label for="dob" style="margin-left:10%">Date of Birth</label> 	<div class="input-field col s12"> 		<i class="material-icons prefix">D</i> 		<input id="dob" name="dob" type="date" class="validate" value="@Model.DOB.Value.ToString("dd/ MM/ yyyy")">  @*@Model.DOB.Value.ToString("mm/dd/yyyy")*@  	</div> 	<div class="input-field col s12"> 		<i class="material-icons prefix">email</i> 		<input id="email" name="email" type="email" class="validate" value="@Model.email"> 		<label for="email">Email</label> 	</div> 	<div class="input-field col s12"> 		<i class="material-icons prefix">lock_outline</i> 		<input id="password" name="password" type="password" class="validate"> 		<label for="password">Password</label>  	</div> 	<div class="input-field col s12"> 		<i class="material-icons prefix">lock_outline</i> 		<input id="confirmPassword" name="confirmPassword" type="password" class="validate" onkeyup="check()"> 		<label for="confirmPassword">Confirm Password</label> 		<lable name="checkpassword"></lable> 	</div> 	<div class="input-field col s12"> 		<input class="btn waves-effect waves-light" id="submit" type="submit" name="action" style="width:33%; margin-left:20%; margin-bottom:4%"> 	</div> 	@*</div>*@ </form>

    Controller

    public ActionResult Index() {     Session["userID"] = "IT14111884";     string sessionValue = Session["userID"].ToString();     if (Session["userID"].ToString() == null) return View("Login");      person1 = repo.GetPeronById(sessionValue);     var model = person1;     //DateTime da = (DateTime)person1.DOB;     //DateTime date2 = ;     //DateTime.ToString("dd MMM yyyy")     return View(model); }  [HttpPost] public JsonResult saveChanges(person person1) {     person _person = new person();     _person.SID = person1.SID;     _person.FirstName = person1.FirstName;     _person.LastName = person1.LastName;     _person.Address = person1.Address;     _person.Phone = person1.Phone;     _person.DOB = person1.DOB;     _person.password = person1.password;     _person.email = person1.email;     //Session["_person"] = _person;      string sessionValue = Session["userID"].ToString();     bool status;     if (!ModelState.IsValid) return Json(false, JsonRequestBehavior.AllowGet);     status = repo.updatePerson(sessionValue,_person);      return Json(status, JsonRequestBehavior.AllowGet); }  [HttpPost] public ActionResult UploadPhoto(HttpPostedFileBase file) {     if (file != null && file.ContentLength > 0)     {         var user = Session["userID"].ToString();         var fileExt = Path.GetExtension(file.FileName);           if (fileExt.ToLower().EndsWith(".png") || fileExt.ToLower().EndsWith(".jpg"))         {             var fileName = user + ".png";             var filePath = HostingEnvironment.MapPath("~/Content/profile/") + fileName;             var directory = new DirectoryInfo(HostingEnvironment.MapPath("~/Content/profile/"));              if (directory.Exists == false)             {                 directory.Create();             }             ViewBag.FilePath = filePath.ToString();             file.SaveAs(filePath);             return RedirectToAction("Index", new { Message = ManageMessageId.PhotoUploadSuccess });          }         else         {             return RedirectToAction("Index", new { Message = ManageMessageId.FileExtensionError });          }      }     return RedirectToAction("Index", new { Message = ManageMessageId.Error });  }   public enum ManageMessageId {     Error,     PhotoUploadSuccess,     FileExtensionError } 

    Reporsitory class

    public bool updatePerson(string ID,person _objPerson)     {         //_dbContext.people.Add(_objPerson);         person temp = null;         try         {             temp = (from p in _dbContext.people                     where p.SID == ID                     select p).SingleOrDefault();             temp.FirstName = _objPerson.FirstName;             temp.LastName = _objPerson.LastName;             temp.Address = _objPerson.Address;             temp.Phone = _objPerson.Phone;             temp.DOB = _objPerson.DOB;             temp.password = _objPerson.password;             temp.email = _objPerson.email;             //_dbContext.SaveChanges();             //Guid id = _objPerson.Person_ID;             if (_dbContext.SaveChanges() > 0)             {                 return true;             }            }         catch (DbUpdateException e)         {             string msg = (e.InnerException.Message);             //Console.ReadLine();          }         return false;      } 
  • 标签
    易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
    该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!