提交时在同一页面上显示成功消息

时间:2013-07-11 09:58:27

标签: c# asp.net-mvc asp.net-mvc-3

我在视图页面中使用Html.Beginform并使用FormCollection向控制器获取参数我希望在同一ViewPage上返回成功消息作为结果。我是使用以下代码,

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

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

3 个答案:

答案 0 :(得分:11)

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

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

然后在网页上:

<p>@ViewBag.result</p>

答案 1 :(得分: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" />
}

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

我的建议

使用FormCollection时存在以下缺点

Point - 1

如果正在使用FormCollection ...必须Type Cast Primitive Type值必不可少,因为在获取{{1}的特定索引条目时},返回的值是System.Collections.Specialized.NameValueCollection类型。在强类型String

的情况下,不会出现这种情况

问题 - 2

当您提交表单并转到View-Models操作方法,并且Post作为参数存在于操作方法中时,您可以将发布的值发送给您View-Model 。否则,再次编写代码以通过View

发回

enter image description here



Point - 3

我们有可以在TempData/ViewData/ViewBagView Model中实施的数据注释。

enter image description here

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



Point - 4

示例您有以下 HTML

Custom Validations

问题 :我们如何从上面例如从控制器内部访问customAttr1的值

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

替代方案:使用一些jQuery获取自定义属性值,并将其与表单值一起发布到操作方法

另一个选择是将您在自定义属性中获得的内容放入隐藏控件中




这就是原因,我总是喜欢使用<input type="text" name="textBox1" value="harsha" customAttr1 = "MyValue" />

答案 2 :(得分: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');
    }
相关问题