在ASP .Net MVC3中,如何获取用户输入的输入值并处理单击按钮以调用控制器,返回一个新的模型实体,用其属性值更新其他表单输入值 / strong>重新加载整个页面?
步骤:
我已经在Web窗体中完成了这一步,但是对MVC3来说是新手......好吧......好吧:)我在想它可能与Ajax.ActionLink有关吗?我看到的例子涉及提交和保存数据。
理查德
答案 0 :(得分:3)
这是使用MVC3进行Ajax发布的方法。在您的情况下,您将根据服务器的响应更新OnSuccess
回调函数上的表单字段。
第1步
确保您引用了jQuery Ajax库
<script src="@Url.Content("~/Scripts/jquery.unobtrusive-ajax.min.js")" type="text/javascript"></script>
第2步
在视图中使用Ajax.BeginForm帮助器方法生成Ajax感知表单。还提供OnSuccess
javascript回调函数
@using(Ajax.BeginForm("Search",new AjaxOptions
{
HttpMethod = "Post",
OnSuccess = "Loaded"
}))
{
<input type="text" name="q" />
<button type="submit" value="Search">Search</button>
}
<script type="text/javascript">
function Loaded(result) {
alert('result ' + result.Name);
}
</script>
第3步
在操作方法中,执行业务处理并返回JSON结果。在这个例子中,我只返回了一个Model,它将查询附加到名称。
[HttpPost]
public ActionResult Search(string q)
{
return Json(new SampleViewModel { Age = 10 , Name = "John " + q });
}
答案 1 :(得分:1)
您可以简单地使用jquery ajax方法来调用该操作,并让该操作返回您需要的任何值。然后,您可以使用返回的值通过javascript更新其他字段。
$('#button').click(function(){
$.ajax({
url: 'controller/action.aspx',
success: function(data) {
$('.result').html(data);
}
});
});
这是非常通用的解决方案,因为您没有提供代码,所以很难具体。 U可能想要设置数据类型,具体取决于您要发回的内容。一个受欢迎的选择是json。
答案 2 :(得分:0)
如果你想要一个真正的Ajax button
元素,而不是样式黑客或JQuery,它也可能只涉及一点点。遗憾的是MS尚未选择将ActionButton添加到Html和Ajax帮助程序,因为当您删除重复的私有支持方法时,差异实际上非常小(您只需要ActionButton
和{ {1}}方法如下所示。)
最终结果是你可以拥有像ajax动作链接那样触发的真实按钮:
GenerateButton
以下代码基于AjaxExtensions类的反编译,因为许多必需的帮助方法未在HtmlHelper上公开。
@Ajax.ActionButton("Delete", "Delete", "document",
new { id = ViewBag.Id },
new AjaxOptions()
{
Confirm="Do you really want to delete this file?",
HttpMethod = "Get",
UpdateTargetId = "documentlist" },
new { id = "RefreshDocuments"
})
jQuery jQuery junery.unobtrusive-ajax.js只需要进行一些小的更改就可以接受新的按钮对象,因为它非常接近开始。首先,选择器需要接受ajax按钮以及链接,然后href需要来自属性,因此非链接可以提供它(不是严格的浏览器兼容,但现在可以使用)。
public static partial class AjaxExtensions
{
public static MvcHtmlString ActionButton(this AjaxHelper ajaxHelper, string buttonText, string actionName, string controllerName, object routeValuesBlah, AjaxOptions ajaxOptions, object htmlAttributesBlah)
{
// Convert generic objects to specific collections
RouteValueDictionary routeValues = new RouteValueDictionary(routeValuesBlah);
RouteValueDictionary htmlAttributes = HtmlHelper.AnonymousObjectToHtmlAttributes(htmlAttributesBlah);
if (string.IsNullOrEmpty(buttonText))
throw new ArgumentException("Button text must be provided");
string targetUrl = UrlHelper.GenerateUrl((string)null, actionName, controllerName, routeValues, ajaxHelper.RouteCollection, ajaxHelper.ViewContext.RequestContext, true);
return MvcHtmlString.Create(GenerateButton(ajaxHelper, buttonText, targetUrl, AjaxExtensions.GetAjaxOptions(ajaxOptions), htmlAttributes));
}
public static string GenerateButton(AjaxHelper ajaxHelper, string linkText, string targetUrl, AjaxOptions ajaxOptions, IDictionary<string, object> htmlAttributes)
{
TagBuilder tagBuilder = new TagBuilder("input");
tagBuilder.MergeAttribute("value", linkText);
tagBuilder.MergeAttributes<string, object>(htmlAttributes);
tagBuilder.MergeAttribute("href", targetUrl);
tagBuilder.MergeAttribute("type", "button");
if (ajaxHelper.ViewContext.UnobtrusiveJavaScriptEnabled)
tagBuilder.MergeAttributes<string, object>(ajaxOptions.ToUnobtrusiveHtmlAttributes());
else
tagBuilder.MergeAttribute("onclick", AjaxExtensions.GenerateAjaxScript(ajaxOptions, "Sys.Mvc.AsyncHyperlink.handleClick(this, new Sys.UI.DomEvent(event), {0});"));
return tagBuilder.ToString(TagRenderMode.Normal);
}
private static string GenerateAjaxScript(AjaxOptions ajaxOptions, string scriptFormat)
{
string str = ajaxOptions.ToJavascriptString();
return string.Format((IFormatProvider)CultureInfo.InvariantCulture, scriptFormat, new object[1] { str });
}
private static AjaxOptions GetAjaxOptions(AjaxOptions ajaxOptions)
{
if (ajaxOptions == null)
return new AjaxOptions();
else
return ajaxOptions;
}
public static string ToJavascriptString(this AjaxOptions ajaxOptions)
{
StringBuilder stringBuilder = new StringBuilder("{");
stringBuilder.Append(string.Format((IFormatProvider)CultureInfo.InvariantCulture, " insertionMode: {0},", new object[1]
{
ajaxOptions.InsertionModeString()
}));
stringBuilder.Append(ajaxOptions.PropertyStringIfSpecified("confirm", ajaxOptions.Confirm));
stringBuilder.Append(ajaxOptions.PropertyStringIfSpecified("httpMethod", ajaxOptions.HttpMethod));
stringBuilder.Append(ajaxOptions.PropertyStringIfSpecified("loadingElementId", ajaxOptions.LoadingElementId));
stringBuilder.Append(ajaxOptions.PropertyStringIfSpecified("updateTargetId", ajaxOptions.UpdateTargetId));
stringBuilder.Append(ajaxOptions.PropertyStringIfSpecified("url", ajaxOptions.Url));
stringBuilder.Append(ajaxOptions.EventStringIfSpecified("onBegin", ajaxOptions.OnBegin));
stringBuilder.Append(ajaxOptions.EventStringIfSpecified("onComplete", ajaxOptions.OnComplete));
stringBuilder.Append(ajaxOptions.EventStringIfSpecified("onFailure", ajaxOptions.OnFailure));
stringBuilder.Append(ajaxOptions.EventStringIfSpecified("onSuccess", ajaxOptions.OnSuccess));
--stringBuilder.Length;
stringBuilder.Append(" }");
return ((object)stringBuilder).ToString();
}
public static string InsertionModeString(this AjaxOptions ajaxOptions)
{
switch (ajaxOptions.InsertionMode)
{
case InsertionMode.Replace:
return "Sys.Mvc.InsertionMode.replace";
case InsertionMode.InsertBefore:
return "Sys.Mvc.InsertionMode.insertBefore";
case InsertionMode.InsertAfter:
return "Sys.Mvc.InsertionMode.insertAfter";
default:
return ((int)ajaxOptions.InsertionMode).ToString((IFormatProvider)CultureInfo.InvariantCulture);
}
}
public static string EventStringIfSpecified(this AjaxOptions ajaxOptions, string propertyName, string handler)
{
if (string.IsNullOrEmpty(handler))
return string.Empty;
return string.Format((IFormatProvider)CultureInfo.InvariantCulture, " {0}: Function.createDelegate(this, {1}),",
new object[2]
{
propertyName,
handler
});
}
public static string PropertyStringIfSpecified(this AjaxOptions ajaxOptions, string propertyName, string propertyValue)
{
if (string.IsNullOrEmpty(propertyValue))
return string.Empty;
string str = propertyValue.Replace("'", "\\'");
return string.Format((IFormatProvider)CultureInfo.InvariantCulture, " {0}: '{1}',",
new object[2]
{
propertyName,
str
});
}
}
*注意:这是在回答日期使用最新版本的所有内容(MVC 5)