【发布时间】:2017-02-17 17:22:35
【问题描述】:
您好,我不知道这是否可能,这就是为什么我需要建议来实现这一点的原因。问题是我想将 javacript 对象与 ajax-beginform 而不是模型对象发布到控制器。我像下面这样编码但找不到发布数据的方法,我知道 jQuery ajax 是一种选择,但在这种情况下我不想使用 jQuery ajax 来发布数据。
HTML
@{
ViewBag.Title = "Index";
Layout = "~/Views/Shared/_Layout.cshtml";
}
@section scripts{
<script type="text/javascript">
var getValues=function()
{
//alert(1)
var v = {
id: $("#txtid").val(), name: $("#txtName").val()
}
console.log(v)
return v;
}
</script>
}
<h2>Index</h2>
@using (Ajax.BeginForm("postvalue", new AjaxOptions { HttpMethod="POST", OnBegin = "getValues" }))
{
<input type="text" id="txtid" />
<br />
<input type="text" id="txtName" />
<br />
<button type="submit" value="Click" style="width:50px;height:50px">Click</button>
}
控制器
namespace AjaxBeginForm.Controllers
{
public class AjaxBeginFormController : Controller
{
// GET: AjaxBeginForm
public ActionResult Index()
{
return View();
}
public void postvalue(searchValues objsearchValues)
{
}
}
public class searchValues
{
public Int64 id { get; set; }
public string name { get; set; }
}
}
我想将数据发布到控制器并在 objsearchValues 中捕获它们。
【问题讨论】:
-
您不想使用
$.ajax()?为什么不? (你认为Ajax.BeginForm()做了什么 - 它使用$.ajax()发布数据,所以你已经在幕后使用它) -
这就是为什么我不想再次使用它。我只想附加一个带有值的对象。有可能吗?
-
什么意思我不想再用这个了?又用什么?为什么你不只是使用
$.ajax()? -
当我们在 mvc 中有内置功能时,我想尽量减少使用 javascript。
-
认真的吗?正确生成控件(使用
name="id"和name="name"及其$.post('@Url.Action("postvalue")', $('form').serialize(), function(data) { ... })- 即您当前拥有的代码更少。
标签: javascript jquery ajax asp.net-mvc unobtrusive-ajax