返回部分视图和消息

rad*_*byx 1 javascript asp.net-mvc asp.net-mvc-partialview asp.net-mvc-5

我有一个部分视图,可以更改连接字符串.提交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>
}
Run Code Online (Sandbox Code Playgroud)

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;
});
Run Code Online (Sandbox Code Playgroud)

行动:编辑

[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.");
}
Run Code Online (Sandbox Code Playgroud)

Ren*_*újo 8

使用扩展方法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()});
}
Run Code Online (Sandbox Code Playgroud)

PS.我建议你创建一个模型来定义Ajax的回报,有Status,MessageAjaxReturn.这样,您的ajax请求将始终返回相同的对象类型.对于该Status属性,您可以创建一个枚举.

你的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);
    }
});
Run Code Online (Sandbox Code Playgroud)