Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/shell/5.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Javascript 返回部分视图和消息_Javascript_Asp.net Mvc_Asp.net Mvc 5_Asp.net Mvc Partialview - Fatal编程技术网

Javascript 返回部分视图和消息

Javascript 返回部分视图和消息,javascript,asp.net-mvc,asp.net-mvc-5,asp.net-mvc-partialview,Javascript,Asp.net Mvc,Asp.net Mvc 5,Asp.net Mvc Partialview,我有一个partialview,可以在其中更改连接字符串。提交编辑时,将调用操作。如果我想让用户再次尝试,我想从这里返回并重新打开局部视图。如果一切顺利(或崩溃),我想调用JavaScript函数Logout,该函数将用户注销并重定向到某个起始页 两种解决方案都有效,只是不能同时使用。我显然缺少一些最佳实践,我该怎么办 局部视图:编辑设置 @model WebConsole.ViewModels.Setting.SettingViewModel @using (Ajax.BeginForm("

我有一个partialview,可以在其中更改连接字符串。提交
编辑时,将调用
操作。如果我想让用户再次尝试,我想从这里返回并重新打开局部视图。如果一切顺利(或崩溃),我想调用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>
}
操作:编辑

$('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.");
}

您可以返回空间视图,初始化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)
{
@ViewBag.ErrorMsg
}

我希望这会有所帮助。

使用扩展方法和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()});
}
$.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);
    }
});
另外,我建议您创建一个模型来定义Ajax返回,其中包含
状态
消息
AjaxReturn
。这样,ajax请求将始终返回相同的对象类型。对于
Status
属性,可以创建枚举

您的ajax请求如下所示:

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()});
}
$.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或
返回RedirectToAction(“索引”)。如果不是,则设置
hasErros=true和自定义的
错误消息

在视图中,将错误块放置在用户可以看到的位置:

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

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

是的,我也想到了,仅使用该模型。我认为这是一个黑客行为,但可能没问题,我会尝试一下-谢谢:)@Darin Dimitrov,MVC之神,不要推荐ViewBag:是的,不要使用ViewBag,但是在动作中设置“某物”的想法,JavaScript可以用来做一件事,或者其他的,我认为仍然可以应用。如果有更好的答案,我仍然愿意接受其他答案看看这个答案:@RenanAraújo我不需要将视图渲染为字符串。在我注销用户并将其重定向到startpage之前,我需要知道客户端是否从操作返回了我的结果(消息),是我需要再次呈现的部分视图,还是我需要向用户提示的消息。:)@RenanAraújo请告诉我,如果我错了,我现在就这么说。也许我还不明白。嗨@radbyx我发布了一个答案,太长了,无法在评论中说:)真正隐藏的bug在这里,我在2½天后发现了它!“UpdateTargetId=“div”,因为它无法与“$('#myModal.modal body').html(message);”一起工作,部分视图已呈现,看起来一切正常,但第二个ajax调用不会返回。现在使用“UpdateTargetId”就可以了:)您的意思是:“AjaxReturn=RenderViewToString(PartialView(“EditSetting”,model))}”);”而不是“AjaxReturn=RenderViewToString(PartialView(“EditSetting,model”)。ViewName,model)}”);“您的代码可以使用我所做的编辑,除非用户在第一次尝试时输入错误。可能是我的编辑,我使用了“.ViewName”,或者可能是javascript闭包中不再记得的“$self”,我不知道?你是对的,要使用该方法,你需要像以前那样使用它。我将方法改为Ted Nyberg创建的
RenderToString
,我认为现在更干净了,所以最终一切都能正常工作。您的代码是正确的,但我错误地更新了DOM元素。我应该用“TargetUpdateId”来代替。之前,我的第二次ajax调用是否因为某种奇怪的原因而从未调用“成功”?!RenanAraújo似乎无法通过这种方式显示ModelState错误。控制器:ModelState.addmodeleror(string.Empty,@“并非所有输入都有效”);视图:@Html.ValidationSummary(true,“,new{@class=“text danger”})$('#updateTargetEditSetting').html(data.AjaxReturn)//$('#myModal.modal body').html(data.AjaxReturn);(这将显示错误,但是如果我再次调用ajax,它将不会返回到“success”,因为我不知道什么奇怪的原因,有什么想法吗?:)