2013-07-11 71 views
4

我在查看页面中使用Html.Beginform并使用FormCollection获取参数给控制器我想在同一ViewPage上返回成功消息,因此使用以下代码,提交时在同一页上显示成功消息

public string InsertDetails(FormCollection collection) 
{  
    string result = "Record Inserted Successfully!"; 
    return result; 
} 

它显示了新页面上的成功消息。我该如何解决这个问题?我必须返回什么才能在同一页面上获得成功消息?

回答

9

就我个人而言,我会弹出结果字符串到ViewBag中。

public ActionResult InsertDetails(FormCollection collection) 
       { 
       //DO LOGIC TO INSERT DETAILS 
       ViewBag.result = "Record Inserted Successfully!"; 
       return View(); 
       } 
然后在网页上

<p>@ViewBag.result<p/> 
+0

请注意,确保您返回正确的视图。注意到这个控制器动作并没有以[HttpPost]开始[我猜这不是视图最初被调用的方法 –

9

我有以下选项。

1.使用Ajax开始形成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" /> 
} 

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() { }) 

我建议

有以下不足之处ES同时使用的FormCollection

点 - 1

如果FormCollection正在使用......这将是强制性的Type CastPrimitive Type值未必然,因为在获取System.Collections.Specialized.NameValueCollection的特定指数的进入,返回的值是String。在强类型View-Models的情况下不会出现这种情况。

问题 - 2

当您提交表单,并进入Post操作方法,并作为View-Model参数在操作方法存在,你必须提供给发布值发送给您View。否则,再编写代码通过TempData/ViewData/ViewBag

enter image description here



点送回去 - 3

我们有数据注释,可以在View ModelCustom Validations实现。

enter image description here

ASP.Net MVC简化了使用数据注释模型validatons。数据注释是属性thyat应用于属性的属性。我们可以通过继承内置的验证属性类来创建自定义验证属性。



点 - 4

例如,你有以下HTML

<input type="text" name="textBox1" value="harsha" customAttr1 = "MyValue" /> 

问题:我们怎样才能从访问customAttr1的价值以上,例如来回m内部控制器

答案:当表单发布时,只有元素的名称和值被发回服务器。 您还可以使用隐藏字段将属性发布到发布操作方法

替代:使用位的jQuery到与表单值的操作方法相处的自定义属性值,和后

另一种选择是,而把你所得到的在自定义的隐藏属性控件




这就是原因,我总是喜欢使用View-Models

0

,我们可以做到这一点的Form里面查看

@using (Ajax.BeginForm("Action", "Controller", new AjaxOptions { HttpMethod = "POST", OnSuccess = "Showmessage" })) 

    [HttpPost] 
    public ActionResult Test(TestViewModel model) 
    { 
     return Json(new {isok=true, message="Your Message" });   
    } 

    function Showmessage(data) 
    { 
     $('#Element').html('Successfully Submitted'); 
    } 
相关问题