简体   繁体   English

asp.net mvc,如果在视图中不起作用

[英]asp.net mvc if else not working in view

This is my part of code from view called index index角度来看,这是我代码的一部分

  <div class="box-body">
                    @{ Html.RenderAction("_BlogsGrid",new {country=""});}
  </div>
  ...
  ...
<script>
    $("#SelectedCountry").change(function () {
        var selectedCountry = $(this).val();
        $.ajax({
            url: '@Url.Action("_BlogsGrid","Blog")' + '?country=' + selectedCountry,
            sucess: function(xhr, data) {
                console.log('sucess');
            },
            error: function (err) {
                console.log(err);
            }

    });
    });
</script>

Here is the controller action code 这是控制器动作代码

public ActionResult _BlogsGrid(string country)
{
    var blogs = _blogService.GetBlogWithCountryName(country).ToList();
    var blogsList = BlogMapper.ToBlogIndex(blogs);
    return PartialView(blogsList);
}

and here is _BlogsGrid view 这是_BlogsGrid视图

@model  Blog.BlogsList
<div class="pull-right">
    @Html.DropDownListFor(m => m.SelectedCountry, new SelectList(Model.CountriesList), "Select a country", new { @class = "form-control" })
</div>
<br />
<br />
@if (Model.Blogs.Count == 0)
{
    <div class="box-group">
        <h4>Sorry we couldn't find any blog related to the country you asked for.</h4>
        @Html.DisplayText("Hello world!")
    </div>
}
else
{
    <div class="box-group" id="accordion">
        @foreach (var blog in Model.Blogs)
        {
            @*Some code*@
        }
    </div>
}

Thing is when i load it first time everything works fine, the controllers method gets hit and all the blogs get loaded this is how the view looks 问题是,当我第一次加载它时,一切正常,控制器方法被命中,所有博客都被加载,这就是视图的外观 在此处输入图片说明

but when I select a country from dropdown list and there are no blogs matching that country 但是当我从下拉列表中选择一个国家时,没有匹配该国家的博客 在此处输入图片说明

it hits the if condition(putting a breakpoint in view I check if if condition is being executed or else condition is being executed, and it goes through if condition) in view (which is a partial view) 它在视图(是局部视图)中命中if条件(在视图中放入断点,我检查是否正在执行条件或正在执行条件,并且通过if条件) 在此处输入图片说明 but the content of "if" is not loaded in the browser. 但是“ if”的内容未加载到浏览器中。 I am still getting same content as before. 我仍然得到与以前相同的内容。 Any idea why my content is not being updated? 知道为什么我的内容没有被更新吗?

Update: 更新:

 <div id="grid" class="box-body">
                        @{ Html.RenderAction("_BlogsGrid",new {country=""});}
 </div>

<script>
    $("#SelectedCountry").change(function () {
        var selectedCountry = $(this).val();

        $.ajax({
            url: '@Url.Action("_BlogsGrid","Blog")' + '?country=' + selectedCountry,
            sucess: function (data) {
                $('#grid').html(data);
            },
            error: function (err) {
                console.log(err);
            }

    });
    });
</script>

in browser response 在浏览器响应中 在此处输入图片说明

But still my div is not updating. 但是我的div仍然没有更新。

As others suggested, you're not updating your div content. 正如其他人建议的那样,您不会更新div内容。 That's way yo don't notice a change when the AJAX call is completed. 这样,您就不会在AJAX调用完成时注意到更改。

To ease things, in addition to .ajax() , jQuery provides the .load() method, which automatically fed the returned content into the matched elements. 为了减轻.ajax() ,除了.ajax() ,jQuery还提供了.load()方法,该方法自动将返回的内容馈送到匹配的元素中。 So your javascript could look like so: 因此,您的JavaScript可能如下所示:

<script>
    $("#SelectedCountry").change(function () {
        var selectedCountry = $(this).val();
        $("div.box-body").load('@Url.Action("_BlogsGrid","Blog")', 'country=' + selectedCountry);
    });
</script>

When the page is created, Razor replace all @ by their value to generated the whole HTML page. 创建页面后,Razor将所有@替换为其值,以生成整个 HTML页面。 This is why in debug mode, your @Html.DisplayText is hit. 这就是为什么在调试模式下,您的@Html.DisplayText@Html.DisplayText原因。

However, when you load the page, the if is taken into account, and if the condition is false, you don't see the inner HTML. 但是,在加载页面时,将考虑if ,并且如果条件为false,则看不到内部HTML。

To update your DOM, you have to use the data parameter of the success ajax call. 要更新DOM,必须使用success ajax调用的data参数。 This parameter is automatically set by the return of your _BlogsGrid method. 该参数由_BlogsGrid方法的返回自动设置。

You can see it by modifying your success callback. 您可以通过修改success回调来查看它。 Note that the data parameter should be the first parameter 注意data参数应该是第一个参数

sucess: function(data) {
    console.log(data);
 },

You're not updating the data after the initial load. 初始加载后,您无需更新数据。 Your ajax call returns the html content of your partial view. 您的ajax调用返回部分视图的html内容。 You'd have to update it to the DOM manually. 您必须手动将其更新为DOM。 Give your container div an id . 给您的容器div一个id

<div id="blogs-grid" class="box-body">
     @{ Html.RenderAction("_BlogsGrid",new {country=""});}
 </div>

And then in your ajax success callback: 然后在您的ajax成功回调中:

sucess: function(data) {
     $('#blogs-grid').html(data);
 },

Now whatever content your ajax returned will be bound to the blogs-grid div 现在,您的ajax返回的任何内容都将绑定到blogs-grid div

Your ajax success function does nothing with the server response. 您的ajax成功函数对服务器响应不起作用。 It just print success in the browser console. 它只是在浏览器控制台中打印成功。

You need to use the server response on the success function and replace the atual content of the page with the new content. 您需要在成功功能上使用服务器响应,并用新内容替换页面的常规内容。

Your html response is the first argument from success function. 您的html响应是成功函数的第一个参数。 You can look at jquery documentantion for better undertanding ( http://api.jquery.com/jquery.ajax/ ) 您可以查看jquery documentantion以获得更好的理解( http://api.jquery.com/jquery.ajax/

To replace the content of your page the success function should be like that: 要替换页面的内容,成功函数应如下所示:

sucess: function(data) {
            $("div.box-body").html(data);
            console.log('sucess');
        },

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM