use*_*925 6 c# asp.net-mvc asp.net-mvc-3
我Html.Beginform在视图页面中使用并获取参数使用FormCollection到控制器我希望返回Success消息与结果相同.ViewPage我使用以下代码,
public string InsertDetails(FormCollection collection)
{
string result = "Record Inserted Successfully!";
return result;
}
Run Code Online (Sandbox Code Playgroud)
它在新页面上显示成功消息.如何解决此问题?我必须返回以在同一页面上获取成功消息?
dor*_*e01 12
我个人将结果字符串弹出到ViewBag中.
public ActionResult InsertDetails(FormCollection collection)
{
//DO LOGIC TO INSERT DETAILS
ViewBag.result = "Record Inserted Successfully!";
return View();
}
Run Code Online (Sandbox Code Playgroud)
然后在网页上:
<p>@ViewBag.result</p>
Run Code Online (Sandbox Code Playgroud)
SCV*_*SCV 11
我有以下选项.
1.使用Ajax Begin Form和AjaxOptions,如下所示
@using (Ajax.BeginForm("ActionName", "ControllerName", new { area = "AreaName" }, new
AjaxOptions
{
HttpMethod = "POST",
OnSuccess = "alert('Success');" //This will execute once the Ajax call is finished.
}, null))
{
<input type="submit" name="nameSubmit" value="Submit" />
}
Run Code Online (Sandbox Code Playgroud)
2.使用JQuery手动设置XHR请求
$.ajax({
url: "@Url.Action("ActionName", "ControllerName", new { area = "AreaName" });",
type: 'POST',
contentType: 'application/json; charset=utf-8',
data: JSON.stringify({param : Value})
})
.done(function () { alert('Success');}) //This will execute when you request is completed.
.fail(function () { })
Run Code Online (Sandbox Code Playgroud)
我的建议
使用FormCollection时存在以下缺点
点 - 1
如果FormCollection正在使用......这将是强制性Type Cast的Primitive Type价值观未不一定是因为当得到的特定指数的进入System.Collections.Specialized.NameValueCollection,返回值的类型的String.在强类型的情况下不会出现这种情况View-Models.
问题 - 2
当您提交表单并转到PostAction Method,并且Action方法中View-Model存在Parameter时,您可以将发布的值发回给您View.否则,再次编写代码以通过发送回来TempData/ViewData/ViewBag

点 - 3
我们有可以在View Model或中实现的数据注释Custom Validations.

ASP.Net MVC使用Data Annotation简化了模型验证.数据注释是在属性上应用thyat的属性.我们可以通过继承内置的Validation Attribute类来创建自定义验证属性.
点 - 4
示例您有以下HTML
<input type="text" name="textBox1" value="harsha" customAttr1 = "MyValue" />
Run Code Online (Sandbox Code Playgroud)
问题:我们如何从上面例如从控制器内部访问customAttr1的值
答案:当表单发布时,只将元素的名称和值发回服务器.您还可以使用"隐藏字段"将"属性"发布到"后置操作"方法.
替代方法:使用一些jQuery来获取自定义属性值,并将其与表单值一起发布到操作方法
另一个选择是将您在自定义属性中获得的内容放入隐藏控件中
这就是原因,我总是喜欢使用 View-Models
| 归档时间: |
|
| 查看次数: |
39756 次 |
| 最近记录: |