返回部分视图和消息

时间:2015-12-03 12:43:22

标签: javascript asp.net-mvc asp.net-mvc-5 asp.net-mvc-partialview

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

两种解决方案都有效,而不是一起使用。我显然错过了一些最佳实践,我该怎么办?

部分视图:编辑设置

@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.");
}

3 个答案:

答案 0 :(得分:8)

使用RenderToString上的扩展程序cacois answer和basead,你可以像这样创建你的行动:

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

聚苯乙烯。我建议您使用StatusMessageAjaxReturn创建一个定义Ajax返回的模型。这样,您的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);
    }
});

答案 1 :(得分:0)

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

控制器:

[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>
}

我希望有所帮助。

答案 2 :(得分:0)

向ViewModel添加错误处理:

bool hasErrors;
string errorMessage;

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

在视图中,将错误阻止用户将看到的位置:

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

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