我想使用Id搜索我的数据并将其显示在html表中(搜索原因(但当我在浏览器上执行代码时,点击搜索按钮后,它只显示表格(表格的设计(,没有任何数据。我在谷歌上搜索得到提示,但没有找到任何合适的帮助。
控制器逻辑:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using WebApp.Controllers;
using WebApp.Models;
namespace WebApp.Controllers
{
public class SearchByIdController : Controller
{
MvcTstEntities ob = new MvcTstEntities();
// GET: SearchById
public ActionResult Index()
{
return View();
}
public JsonResult Search(string mail)
{
var str = (from test in ob.Emp where test.EmailId == mail select test).FirstOrDefault();
return Json(str, JsonRequestBehavior.AllowGet);
}
}
}
查看逻辑
<body>
<form class="form-inline">
<div class="form-group mx-sm-3 mb-2">
<label for="exampleInputEmail1">Email</label>
<input type="email" class="form-control" id="exampleInputEmail1" aria-describedby="emailHelp" placeholder="Enter email">
</div>
<button type="button" id="btnsearch" class="btn btn-primary mb-2">Search</button>
</form>
<div>
<div class="container" id="tbleshow">
<table class="table table-striped">
<tr>
<th>ID</th>
<th>Name</th>
</tr>
<tr>
<td id="ide" ></td>
<td id="nm"></td>
</tr>
</table>
</div>
</div>
<script type="text/javascript">
$(document).ready(function () {
$("#tbleshow").hide();
$("#btnsearch").click(function (e) {
debugger
e.preventDefault();
$("#tbleshow").show();
return myfunction();
});
function myfunction() {
var model = {
Email: $("#exampleInputEmail1").val(),
}
$.ajax({
type: 'GET',
url: "/SearchById/Search",
dataType: 'json',
data: {
Email: model.Email,
},
success: function (run) {
$("#ide").val(run.EmailId);
$("#nm").val(run.Name);
if (run) {
alert("This is the details");
}
else {
alert("Something wrong in success");
}
},
error: function () {
console.log('something went wrong - debug it!');
}
});
}
});
</script>
</body>
有人能告诉我如何从控制器获取表上的值并将其绑定到表上吗。
问题是您使用的操作方法以mail
为参数名称:
public JsonResult Search(string mail)
但是在AJAX调用的data
属性中包含Email
参数,如下所示,它与控制器操作方法中定义的参数名称不匹配
$.ajax({
type: 'GET',
url: "/SearchById/Search",
dataType: 'json',
data: {
Email: model.Email, // this is the wrong part
},
success: function (run) {
// show the results
},
error: function () {
console.log('something went wrong - debug it!');
}
});
为了符合AJAX参数名称,您应该将操作参数名称更改为Email
:
public JsonResult Search(string Email)
{
var str = (from test in ob.Emp
where test.EmailId == Email
select test).FirstOrDefault();
return Json(str, JsonRequestBehavior.AllowGet);
}
或者保持控制器操作原样,但更改AJAX参数名称以与控制器操作参数名称匹配:
$.ajax({
type: 'GET',
url: "/SearchById/Search",
dataType: 'json',
data: {
mail: $("#exampleInputEmail1").val() // this is correct
},
success: function (run) {
// show the results
},
error: function () {
console.log('something went wrong - debug it!');
}
});
更新:
如果run
包含JSON字符串而不是对象,则需要首先解析该字符串:
var obj = JSON.parse(run);
然后使用该对象显示值:
$("#ide").val(obj.EmailId);
$("#nm").val(obj.Name);