常见问题一之拼接表格 js传递参数变量 Json接收值
1.前台拼接表格时,有时候需要使用拼接html字符串,需要多次循环拼接的,放在方法里边:
//ary可以是数组中的一组数据.
function(ary)
{
var MyHtml="<tr>";
MyHtml+="<td>" + ary.ID + "</td>";
MyHtml+="<td>" + '<input type="radio" name="toggle" valuestr="'+ary.Name+'"/>' + "</td>";
MyHtml="</tr>";
}
2.利用javascript和@url.action()传递参数变量。
//url字符串
var urlstr = '@Url.Action("Index", "Home")' + "?Id=" +id; //更改
$("#btnok").attr("href", urlstr);
3.利用从json后台传送一个实体类到前台。
public JsonResult JsonTest() { var Model = db.Model.First(x => true); //var Model = db.Model.Where(x => true).Take(1).ToList(); //序列化对象 string str = JsonConvert.SerializeObject(Model); return Json(str); } //前台接收 $("#btnok2").click(function () { $.ajax({ type: "post", url: "@Url.Action("JsonTest", "Home")", data: { }, //传递json字符串 需要使用 JSON.stringify(ary) cache: false, dataType: "json", success: function(data) { var ary2 = JSON.parse(data); alert(ary2.ID + "." + ary2 + "," + ary2.Name); //alert(ary2[0].ID + "." + ary2 + "," + ary2[0].Name); } })
4.json传递数据方式二:传递一个List<JsonClass>。
public JsonResult JsonTest2(int id) { string str = string.Empty; if (id == 1) { JsonClass jsonClass = new JsonClass() { ID = 1, Name = "xx", Sex = "男" }; List<JsonClass> list = new List<JsonClass>(); list.Add(jsonClass); list.Add(new JsonClass { ID = 2, Name = "oo", Sex = "女" }); str = JsonConvert.SerializeObject(list); } return Json(str, JsonRequestBehavior.AllowGet); } //定义类别 public class JsonClass { public int ID { get; set; } public string Name { get; set; } public string Sex { get; set; } }
5.接收前台传过来的Json字符串
[HttpPost] public ActionResult Edit(string ary) { // ary = "[{\"type\":\"0\",\"Id\":\"3\",\"serial\":\"2\"},{\"type\":\"0\",\"Id\":\"2\",\"serial\":\"1\"}]"; var emply = new { ID = 0, Name = string.Empty,Sex = string.Empty }; if (ary.Length>0) { JArray jsonary = (JArray)JsonConvert.DeserializeObject(ary); string str = string.Empty; for(int i=0;i<jsonary.Count;i++) { JObject obj = (JObject)jsonary[i]; var array = JsonConvert.DeserializeAnonymousType(obj.ToString(), emply); str += array.ID + array.Name + array.Sex; //第二种接收值方式: int Id; string Name, Sex; Id = Convert.ToInt32(obj["ID"].ToString()); Name = obj["Name"].ToString(); Sex = obj["Sex"].ToString(); } } return RedirectToAction("Index"); } }
以上为平时遇到,或者遇到后又遗忘的一些些问题。备以记录,以供查询。