返回部分视图和消息

我有一个partialview可以更改连接字符串。 提交Edit操作时被调用。 从这里我想要返回并重新打开局部视图,如果我希望用户有第二次去。 如果一切顺利(或崩溃),我想调用我的JavaScript函数Logout ,它将用户注销并重定向到某个首页。

两种解决方案都有效,只是不在一起 我显然错过了一些最佳做法,我该怎么办?

部分视图:EditSetting

@model WebConsole.ViewModels.Setting.SettingViewModel

@using (Ajax.BeginForm("Edit", "Setting", new AjaxOptions { UpdateTargetId = "div" }, new { id = "editform" }))
{
    <fieldset>
        @Html.AntiForgeryToken()

        <div class="form-horizontal">
            @Html.ValidationSummary(true, "", new {@class = "text-danger"})

            <div class="form-group">
                @Html.LabelFor(model => model.User, htmlAttributes: new {@class = "control-label col-md-2"})
                <div class="col-md-10">
                    @Html.EditorFor(model => model.User, new {htmlAttributes = new {@class = "form-control"}})
                    @Html.ValidationMessageFor(model => model.User, "", new {@class = "text-danger"})
                </div>
            </div>

            <div class="form-group">
                @Html.LabelFor(model => model.Password, htmlAttributes: new {@class = "control-label col-md-2"})
                <div class="col-md-10">
                    <input type="password" name="Password" id="Password" value=""/>
                    @Html.ValidationMessageFor(model => model.Password, "", new {@class = "text-danger"})
                </div>
            </div>

            <div class="form-group">
                @Html.LabelFor(model => model.DataSource, htmlAttributes: new {@class = "control-label col-md-2"})
                <div class="col-md-10">
                    @Html.EditorFor(model => model.DataSource, new {htmlAttributes = new {@class = "form-control"}})
                    @Html.ValidationMessageFor(model => model.DataSource, "", new {@class = "text-danger"})
                </div>
            </div>

            <div class="form-group">
                @Html.LabelFor(model => model.InitialCatalog, htmlAttributes: new {@class = "control-label col-md-2"})
                <div class="col-md-10">
                    @Html.EditorFor(model => model.InitialCatalog, new {htmlAttributes = new {@class = "form-control"}})
                    @Html.ValidationMessageFor(model => model.InitialCatalog, "", new {@class = "text-danger"})
                </div>
            </div>
        </div>
    </fieldset>
}

JavaScript:提交

$('form').submit(function () {
    var $self = $(this);

    if ($(this).valid()) {

        // Change Connection String
        $.ajax({
            url: this.action,
            type: this.method,
            data: $(this).serialize(),
            success: function (message) {

                // Use Partial View
                //$('#myModal .modal-body').html(message);

                // Conn Str is now changed. Log out and redirect
                logOut($self, message);
            },
            error: function (message) {
                logOut($self, message);
            }
        });
    }
    return false;
});

行动:编辑

[HttpPost]
public ActionResult Edit(SettingViewModel model)
{
    // Validate inputs
    if (!ModelState.IsValid)
    {
        ModelState.AddModelError("", @"Not all inputs are valid.");
        return PartialView("EditSetting", model);
    }

    var sql = new DAL.SQL(DAL.SQL.GenerateConnectionString(model.DataSource, model.InitialCatalog, model.User, SecurePassword(model.Password)));

    // Validate Connection String
    if (!sql.Open())
    {
        ModelState.AddModelError("", @"Error. Unable to open connection to Database.");
        return PartialView("EditSetting", model);
    }

    // Validate a transaction
    if (!sql.IsRunningTransact())
    {
        ModelState.AddModelError("", @"Error. Unable to connect to Database Server.");
        return PartialView("EditSetting", model);
    }

    // Save Connection String
    BuildAndEncryptConnString(model);

    return Content("The Connection String is changed. Log in again to continue.");
}

使用扩展方法RenderToString和basead on cacois answer,你可以像这样创建你的动作:

public ActionResult Edit(SettingViewModel model)
{
    // "Ifs" to return only partials
    if (ModelState.IsValid)
    {
        return PartialView("EditSetting", model);
    }

    ...

    // Returning a Json with status (success, error, etc), message, and the content of 
    // your ajax, in your case will be a PartialView in string
    return Json(new { 
               Status = 1, 
               Message = "error message", 
               AjaxReturn = PartialView("EditSetting", model).RenderToString()});
}

PS。 我建议你创建一个模型来定义Ajax返回Status ,包括StatusMessageAjaxReturn 。 这样,你的ajax请求将始终返回相同的对象类型。 对于Status属性,您可以创建一个Enum。

您的ajax请求将如下所示:

$.ajax({
    url: this.action,
    type: this.method,
    data: $(this).serialize(),
    success: function (data) {
        if(data.Message == undefined) {
            // Use data like a partial
        } else {
            // Use data.Message for the message and data.AjaxReturn for the partial
        }
    },
    error: function (message) {
        logOut($self, message);
    }
});

将错误处理添加到您的ViewModel中:

bool hasErrors;
string errorMessage;

在您的控制器中,如果数据验证正常,只需返回PartialView或return RedirectToAction("Index"); 。 如果没有,则设置hasErros = true; 和一个自定义的errorMessage

在视图中,放置一个错误,阻止用户看到它的人:

@if (Model.hasErrors)
{
   <div>Model.errorMessage</div>
}

顺便说一下,您可以在ViewModel构造函数中进行数据验证。


您可以返回空间视图,并初始化ViewBag并将消息分配给它,然后在视图中检查是否有值并显示它是否为真。

控制器:

[HttpPost]
public ActionResult Edit(SettingViewModel model)
{
    // Put the ViewBag where ever you want
    ViewBag.ErrorMsg =" Error";
    return PartialView("EditSetting", model);
}

视图:

@if(ViewBag.ErrorMsg !=null )
{
    <div>@ViewBag.ErrorMsg</div>
}

我希望有所帮助。

链接地址: http://www.djcxy.com/p/42105.html

上一篇: Returning both Partial View and a Message

下一篇: Partial view not working on ajax call mvc5