在视图中返回json结果

时间:2013-04-10 18:41:59

标签: ajax asp.net-mvc json

我有一个在PartialView中呈现的简报文本框。这是获取动作:

[ChildActionOnly]
public PartialViewResult NewsLetterSidebar()
{
    return PartialView("_NewsLetterSidebar");
}

这是Razor的观点:

model Blog.Web.UI.ViewModels.NewsLetterViewModel 

@{
    ViewBag.Title = "_NewsLetterSidebar";
}

@using (Html.BeginForm("NewsLetter", "Home", FormMethod.Post))
{
    <h3>News Letter</h3>
    <div>
        @Html.TextBoxFor(news => news.EmailAddress)
        @Html.ValidationMessageFor(news => news.EmailAddress)
    </div>
    <div>
        <input type="submit" value="Verify">
    </div>
}

我希望在有效输入的情况下,成功消息显示在验证按钮下。这是我的帖子:

[HttpPost]
public JsonResult NewsLetter(NewsLetterViewModel newsLetter)
{
    var newsLetterViewModel = newsLetter.ConvertToNewsLetterModel();

    if (ModelState.IsValid)
    {
        _newsLetterRepository.Add(newsLetterViewModel);
        _newsLetterRepository.Save();
    }
    return Json("Done!");
}

如何在View下显示JSON消息?

2 个答案:

答案 0 :(得分:0)

未经测试但会帮助您完成所需的工作。

[HTTPGET]
public JsonResult NewsLetter(NewsLetterViewModel newsLetter)
{
    var newsLetterViewModel = newsLetter.ConvertToNewsLetterModel();

    if (ModelState.IsValid)
    {
        _newsLetterRepository.Add(newsLetterViewModel);
        _newsLetterRepository.Save();
    }
    return Json("Done!", JsonRequestBehavior.AllowGet);
}

替换此

@using (Html.BeginForm("NewsLetter", "Home", FormMethod.Post))
{}

@using (Ajax.BeginForm("NewsLetter", "Home", new AjaxOptions{ onsuccess:"ShowMessage"}))
    {}

JS

function ShowMessage(data){
alert(data);
}

答案 1 :(得分:0)

如果您想使用上述评论中的第一种方法,则需要稍微修改一下代码。首先,将Message属性添加到NewsLetterViewModel,然后更改部分视图:

@using (Ajax.BeginForm("NewsLetter", new AjaxOptions{UpdateTargetId = "newsletter-container"}))
{
    <h3>News Letter</h3>
    <span>@Model.Message</span>
    <div>
        @Html.TextBoxFor(news => news.EmailAddress)
        @Html.ValidationMessageFor(news => news.EmailAddress)
    </div>
    <div>
        <input type="submit" value="Verify">
    </div>
}

请注意,您的部分视图应该包含在页面上带有id="newsletter-container"的html元素中,例如:

<div id="newsletter-container">
    @{Html.RenderPartial("_NewsLetterSidebar", new NewsLetterModel());}
</div>

现在,控制器发生了一些小变化:

[HttpPost]
public ActionResult NewsLetter(NewsLetterViewModel newsLetter)
{
    var newsLetterViewModel = newsLetter.ConvertToNewsLetterModel();

    if (ModelState.IsValid)
    {
        _newsLetterRepository.Add(newsLetterViewModel);
        _newsLetterRepository.Save();
            model.Message = "Done!";
    }

    return PartialView("_NewsLetterSidebar", model);
}

您还需要添加jquery.unobtrusive-ajax.js才能使其正常运行。