简体   繁体   中英

asp.net mvc if else not working in view

This is my part of code from view called 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

@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) 在此处输入图片说明 but the content of "if" is not loaded in the browser. 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.

As others suggested, you're not updating your div content. That's way yo don't notice a change when the AJAX call is completed.

To ease things, in addition to .ajax() , jQuery provides the .load() method, which automatically fed the returned content into the matched elements. So your javascript could look like so:

<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. This is why in debug mode, your @Html.DisplayText is hit.

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.

To update your DOM, you have to use the data parameter of the success ajax call. This parameter is automatically set by the return of your _BlogsGrid method.

You can see it by modifying your success callback. Note that the data parameter should be the first parameter

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. You'd have to update it to the DOM manually. Give your container div an id .

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

And then in your ajax success callback:

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

Now whatever content your ajax returned will be bound to the blogs-grid div

Your ajax success function does nothing with the server response. 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. You can look at jquery documentantion for better undertanding ( 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');
        },

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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