I haven't written it for a long time. During this time, I am busy learning things, mainly asp.net MVC. It feels much easier to use than webform. At the beginning, I felt a lot of thinking and habits were a little unaccustomed. However, after so many days of study, I still felt good, at least I was still finding my feeling,
Not to mention nonsense. I learned about how to add data through ajax today. It is very interesting to stay and use it as a document. Hey hey, here are some examples:
Add the following code on the front-end page:
1 <div> 2 <input type = "text" name = "name" id = "name"/> 3 <button id = "BtnSub"> submit </button> 5 </div>
The running result is as follows:
It looks quite simple, but the principle of it is the main thing. If you understand the principle, you can understand a lot of code in the future.
You can't wait to see how ajax technology (javascript code implementation) is used. The Code is as follows:
1 $(document).ready(function () {2 $("#BtnSub").click(function () {3 var dp = { dpt: $("#name").val() };4 $.post("/Admin/Ajax/AjaxPost",
dp,
function (data) { },
"json")5 });6 });
Hey, it's simple, but it's actually simple. below is the code of C # (based on the Razor view:
1 [HttpPost] 2 public ActionResult AjaxPost(string dpt) 3 { 4 Department d = new Department(); 5 Entities db = new Entities(); 6 JsonResult r = new JsonResult(); 7 d.Name = dpt; 8 try 9 {10 db.Entry(d).State = System.Data.EntityState.Added;11 db.SaveChanges();12 }13 catch (Exception ex)14 {15 r.Data = new { Success = false, Ex = ex.Message };16 }17 18 return r;19 }
Okay, this is almost the case for the Code. Let's take a look at the running effect:
You can see that the data is displayed, but the most important thing is that when you add data, the page is not refreshed. If you don't believe it, try it !!