@{
ViewBag.Title = "Index";
Layout = null;
}
<html>
<head>
<meta name="viewport" content="width=device-width" />
<title>Jquery实现数据双向绑定(赋值和取值)</title>
<script src="https://cdn.bootcss.com/jquery/3.2.1/jquery.js"></script>
<script src="~/Js/JqueryExt.js"></script>
<script>
$(document).ready(function () {
var objData = @Html.Raw(Json.Encode(ViewBag.Data));
//将数据加载到表单中
$.mloadData(objData);
//读取表单中的数据 提交
$("#btnSave").click(function () {
var data = $.mSaveData(objData);
console.log(data);
$.ajax({
type: "post",
timeout : 3000,
url: "@Url.Action("SavaData", "Default")",
data: data,
dataType: "json", //返回数据形式为json
success: function (success) {
alert("操作成功")
},
error: function(XMLHttpRequest, textStatus, errorThrown) {
console.log(XMLHttpRequest.status);
console.log(XMLHttpRequest.readyState);
console.log(textStatus);
alert("操作错误,请稍后尝试")
}
})
});
//objData.area = "张三的各个";
//var a = $.mGetData(objData, "area");
//console.log(a);
});
</script>
</head>
<body>
<div>
<form id="myform" method="post" action="">
<fieldset>
<legend>jquery数据双向绑定</legend>
<table>
<tr>
<td>姓名</td>
<td>
<input type="hidden" name="id" />
<input type="text" name="name" />
</td>
</tr>
<tr>
<td>地区</td>
<td>
<select name="area">
<option value="futian">福田区</option>
<option value="nanshan">南山区</option>
<option value="luohu">罗湖区</option>
</select>
</td>
</tr>
<tr>
<td>性别</td>
<td>
<input type="radio" name="sex" value="male" />男
<input type="radio" name="sex" value="female" />女
</td>
</tr>
<tr>
<td>爱好</td>
<td>
<input type="checkbox" name="hobby" value="movie" />电影
<input type="checkbox" name="hobby" value="music" />音乐
<input type="checkbox" name="hobby" value="basketball" />篮球
</td>
</tr>
<tr>
<td>简介</td>
<td>
<textarea name="intro"></textarea>
</td>
</tr>
<tr>
<td colspan="2" style="text-align:center;">
<input id="btnSave" type="button" value="提交" />
</td>
</tr>
</table>
</fieldset>
</form>
</div>
</body>
</html>
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
namespace MVC_demo.Controllers
{
public class DefaultController : Controller
{
// GET: Default
public ActionResult Index()
{
var model = new Data()
{
id = 1,
name = "张三",
area = "futian",
sex = "male",
hobby = "music,movie",
intro = "你好,世界"
};
ViewBag.Data = model;
return View();
}
public ActionResult SavaData(Data data)
{
var result = new result();
result.success = true;
return Json(result);
}
}
/// <summary>
/// 数据类
/// </summary>
public class Data
{
public int id { get; set; }
public string name { get; set; }
public string area { get; set; }
public string sex { get; set; }
public string hobby { get; set; }
public string intro { get; set; }
}
/// <summary>
/// 通知类
/// </summary>
public class result
{
public bool success;
public string message;
}
}