Rectangle 27 3

option 1. Override rendered content with the result of POST

There is no simple "rebind" method inside mvc, it's still html, css and js at the end. I see 2 options to achieve desired behaviour.

<div id="content">
  <div>
    <p>Order lines allocates to <b>@Model.Name (@Model.Code) </b>
  </div>
  ...
  else
  {
    @Html.Raw("No records found....");
  }
</div>
$.ajax({
    type: 'POST',
    url: '/Batch/GetData',
    dataType: "html",
    success: function(data, textStatus, jqXHR){
        $('#content').html(data);
    }
});
<div>
    <p>Order lines allocates to <b id="NameAndCode"></b>
</div>
$(function(){
  var model = {
    NameAndCode: "@Model.Name (@Model.Code)"
  }

  fillView(model);

})

var fillView = function(data){
  $('#NameAndCode').html(data.NameAndCode)
}

$.ajax({
    type: 'POST',
    url: '/Batch/GetData',
    dataType: "json",
    success: function(data, textStatus, jqXHR){
        fillView(data);
    }
});

It's just a small piece just to show the idea.

I have tried first option, bt it replacing div html with complete view html. I think it first approach I should go for a partial view and replace div html with partial view html.

asp.net mvc - How can I refresh my razor view on AJAX post - Stack Ove...

asp.net-mvc asp.net-mvc-3 jquery razor asp.net-mvc-4
Rectangle 27 3

option 1. Override rendered content with the result of POST

There is no simple "rebind" method inside mvc, it's still html, css and js at the end. I see 2 options to achieve desired behaviour.

<div id="content">
  <div>
    <p>Order lines allocates to <b>@Model.Name (@Model.Code) </b>
  </div>
  ...
  else
  {
    @Html.Raw("No records found....");
  }
</div>
$.ajax({
    type: 'POST',
    url: '/Batch/GetData',
    dataType: "html",
    success: function(data, textStatus, jqXHR){
        $('#content').html(data);
    }
});
<div>
    <p>Order lines allocates to <b id="NameAndCode"></b>
</div>
$(function(){
  var model = {
    NameAndCode: "@Model.Name (@Model.Code)"
  }

  fillView(model);

})

var fillView = function(data){
  $('#NameAndCode').html(data.NameAndCode)
}

$.ajax({
    type: 'POST',
    url: '/Batch/GetData',
    dataType: "json",
    success: function(data, textStatus, jqXHR){
        fillView(data);
    }
});

It's just a small piece just to show the idea.

I have tried first option, bt it replacing div html with complete view html. I think it first approach I should go for a partial view and replace div html with partial view html.

asp.net mvc - How can I refresh my razor view on AJAX post - Stack Ove...

asp.net-mvc asp.net-mvc-3 jquery razor asp.net-mvc-4
Rectangle 27 11

I've tried an Ajax call to the appropriate URL, but it doesn't refresh the display.

That's exactly what you should have use. Let's suppose that you have the following view:

<div id="mainframeContens"></div>

<button id="loadFromMainFrame" data-url="@Url.Action("GetFromMainFrame")">Load from mainframe</button>

and then you could write the following script which will send an AJAX request ti the corresponding controller action when the button is clicked and load the content in the div:

$(function() {
    $('#loadFromMainFrame').click(function(e) {
        e.preventdefault();
        var url = $(this).data(url);
        $('#mainframeContens').load(url);
    });
});

and now all that's left of course is to have the corresponding controller action that will load the data from the mainframe and render a partial view:

public ActionResult GetFromMainFrame()
{
    SomeModel model = ... go hit the mainframe to retrieve the model using a webservice or whatever you are using to hit it
    return PartialView("_SomePartial", model);
}

I'm not able to get this working. Is the button supposed to be in the parent view, or the second page which has only the partial view? I've tried both, but in neither case does my breakpoint in the controller get hit. I'll post my code shortly.

Got it working by adding the quotes, as Francisco pointed out above. Many, many thanks!

You added the quotes where? In this answer where does the url comes from?

jquery - MVC with Razor: how to refresh partial page on click? - Stack...

jquery asp.net-mvc razor
Rectangle 27 1

What I think you are trying to do is refresh a page to reorder a list using the Razor syntax without a page refresh or HTTP call to the server. This is not possible because the View in the ASP.NET MVC world is cshtml definition which is going to execute once per call. You need something running on the client side to refresh the page (ie JavaScript).

A good idea is to output the contents of your model as Json (which you could do in a standard MVC controller (without an associated view) returning a JsonResult using the MVC controller Json function. You could also use a WebApi controller which can produce Json nativly.

You will then need to have some code on the client side to look at that model and reorder it in response to your client interactions. Angular.js and Backbone.js are good contenders for this but there are lots of others.

Right now the methodology i am using is going to controller and again fetching the same records from the existing model, reordering and putting it in View. But because the page is getting refreshed, i was asked to validate it on the view side itself. thanks for the answer. Let me have a look athe the client interaction sites and fetching the solution with the links you provided. @AlexC

c# - Sorting items in a list of MVC view without involvement of contro...

c# javascript asp.net-mvc asp.net-mvc-viewmodel asp.net-mvc-views
Rectangle 27 2

The issue is that the ~ is not valid html or a valid URL. But you can use the URL extension methods within Razor to translate the path for you as it understands the tilde. ASP.NET understands the ~ as the root of your application and will translate it accordingly.

<head>
    <meta http-equiv="refresh" content="3; url=@Url.Content("~/Incidents")">
</head>
<body> 
    <div>
        <p>
            <center>
                <a href="@Url.Content("~/Incidents")">View Incidents</a>
            </center>
        </p>

servicestack Razor page with relative path in meta refresh not served ...

servicestack
Rectangle 27 1

There are a few ways to handle this, one is have your partial view add a hash or querystring to the url, and have handling in your JavaScript or controller to know how to grab the hash/querystring and load the right partial view on the page reload.

But if you need to keep track of what they were doing before hitting reload, you could either use something that is holding their location server-side, or caching client-side. For tips on caching, look at this or this.

I found both work equally well, but going with the hash or querystring will show in the url, not always what you are going for.

I'm not sure what frameworks you are using on the client-side (knockout.js, jQuery, etc.) but a lot of these make this stuff easier, you could create a simple cache of your views on load, adding the needed views to the cache based on whatever order you need them, and just inject it into a div or something when they call for it.

The issue here, is that partial views are like code snippits in a way, the server knows how to dish them up, and the client knows how to view them, but the browser doesn't view them as entries into your browser history so you have to tell the browser how to ensure your data gets reloaded how you want.

Another option you could look at would be injecting them into the browser history, but you still need a way for the server to dish up the right partial on load. I found this here on a guy's implementation of loading partials for single-page web applications, seemed like a good option. But again, you need to know how you are going to dish up that data on a reload. But to answer the comment, there isn't some magical way for the browser to know what you are calling with ajax. if you want the browser to know about it automatically, try using @Html.Partial(string partialViewName) or @Html.RenderPartial(string partialViewName) see MSDN on these.

You could also look into putting something in the viewdata, tempdata, viewbag, or session data look at this article on the differences, to see if one would work for your needs.

There has to be some easier way than these. I would figure since we are up to mvc5 and razor3/4, they would have a simpler way to integrate the back and forward of partial views.

I'd suggest looking at sammy.js read a simple intro/explaination here as one of the nice things it does is allow browser navigation with a single page application - but again you use the hash in the url. - but it is easier than writing it yourself. also check my edit for other options.

javascript - ASP.net Razor Refresh on partial view returns to home pag...

javascript ajax asp.net-mvc razor
Rectangle 27 0

option 1. Override rendered content with the result of POST

There is no simple "rebind" method inside mvc, it's still html, css and js at the end. I see 2 options to achieve desired behaviour.

<div id="content">
  <div>
    <p>Order lines allocates to <b>@Model.Name (@Model.Code) </b>
  </div>
  ...
  else
  {
    @Html.Raw("No records found....");
  }
</div>
$.ajax({
    type: 'POST',
    url: '/Batch/GetData',
    dataType: "html",
    success: function(data, textStatus, jqXHR){
        $('#content').html(data);
    }
});
$(function(){
  var model = {
    NameAndCode: "@Model.Name (@Model.Code)"
  }

  fillView(model);

})

var fillView = function(data){
  $('#NameAndCode').html(data.NameAndCode)
}

$.ajax({
    type: 'POST',
    url: '/Batch/GetData',
    dataType: "json",
    success: function(data, textStatus, jqXHR){
        fillView(data);
    }
});

It's just a small piece just to show the idea.

I have tried first option, bt it replacing div html with complete view html. I think it first approach I should go for a partial view and replace div html with partial view html.

asp.net mvc - How can I refresh my razor view on AJAX post - Stack Ove...

asp.net-mvc asp.net-mvc-3 jquery razor asp.net-mvc-4
Rectangle 27 0

if you want to switch your content dinamically, you have to load data via ajax and then replace the right column of your site...Razor don't have a "automatic mode" to do that. =P

I have some projects using this 'approach'. I render my views as partials views (in controller) and then I get the html and put where I want.

Is it me or this make this whole layout thing a little useless for people like me that try to not waste resource uselessly?

The point of the layout is the same as the point of a master page - to keep you from needing to cut and paste elements that are present on multiple pages.

jquery - Rendering an ASP.NET MVC view in a Razor layout refresh the w...

jquery asp.net-mvc razor
Rectangle 27 0

MVC has a built-in ajax mechanism you can use:

jquery - Rendering an ASP.NET MVC view in a Razor layout refresh the w...

jquery asp.net-mvc razor
Rectangle 27 0

your going at it a little wrong, try doing it with jQuery.

Post the form in ajax and render the view returned, here is a blog post that kind of show how to do it http://bob-the-janitor.blogspot.com/2011/11/more-ajax-with-mvc-using-partial-views.html, I'm working on one that deal specifically with posting forms over ajax and using model based validation on the returned view

ASP.net razor :: how-to send a contact form and don't refresh the page...

asp.net-mvc razor
Rectangle 27 0

Your Ajax.BeginForm() is replacing the contents of <div id="messagelist"> with the html from return PartialView("_posts", msgDetails);. I suspect the model msgDetails contains only the details of the comment's associated message so that's all your seeing.

I suggest to rethink your design, particularly the Messages() method, which after saving the message is calling the database to get all messages and returning the complete list - you already have all the data on the page so this seems completely unnecessary and just degrades performance. You could simplify it with the following

Partial view (note the partial is for one message, not a collection)

@model Model.Message
<div class="message">
  <div class=username">@Model.UserName</div>
  <div class=messagetext">@Model.MessageText</div>
  <div class="commentlist">
    @foreach (var comment in Model.Comments)
    {
      <div class="comment">
        <div class="username">@comment.UserName<div>
        <div class="commenttext">@comment.MessageText<div>
      </div>
    }
  </div>
  <div>
    @Html.TextBox("CommentText", new { placeholder = "Leave a comment", id = "" }) // remove the id attribute so its not invalid html
    <button class="addcomment" data-id="@Model.MessageId">Add Comment</button>
  </div>
</div>
@model myModel
...
@Html.TextArea("Message", new { placeholder = "Add a post" })  // no point adding the id - its already added for you    
<input type="button" id="Post" value="Post" />
<div id="messagelist">
  @foreach(var message in Model.MessageList)
  {
    @{ Html.RenderPartial("_posts", message); }
  }
</div>
<div id="newmessage"> // style this as hidden
  @{ Html.RenderPartial("_posts"); }
</div>
// Add a model or ViewBag property for the current user name
var userName = JSON.parse('@Html.Raw(Json.Encode(ViewBag.UserName))');

$('#Post').click(function () {
  var url = '@Url.Action("Message", "MyController")'; // dont hardcode!
  var message = $('#Message').val();
  $.post(url, { MessageText: message }, function (data) {
    if(data) {
      // clone the new message, update message id and add to DOM
      var html = $('#newmessage').clone();
      message.children('.username').text(userName);
      message.children('.messagetext').text(message);
      message.children('.newcomment').children('button').data('id', data);
      $('#messagelist').perpend(html); // add at top of list
      $('#Message').val(''); // clear message text
    } else {
      // something went wrong
    }
  });
});

$('.addcomment').click(function() {
  var url = '@Url.Action("Comment", "MyController")';
  var comment = $(this).prev('input');
  var messageID = $(this).data('id');
  var list = $(this).closest('.message').children('.commentlist');
  $.post(url, { MessageID: messageID, CommentText comment.val() }, function (data) {
    if (data) {
      // add message
      var html = $('<div><div>').addClass('comment');
      html.append($('<div><div>').addClass('username').text(userName));
      html.append($('<div><div>').addClass('commenttext').text(commentText));
      list.append(html); // add to end of existing comments
      comment.val(''); // clear existing text
    } else {
      // something went wrong
    }
  });
});
[HttpPost]
public ActionResult Message(string MessageText)
{
  // create new message object and save to database
  int ID = // the ID of the new message
  return Json(ID); // if exception, then return null;
}

[HttpPost]
public ActionResult Comment(int MessageID, string CommentText)
{
  // create new comment object and save to database
  return Json(true); // if exception, then return null;
}

Sir, first of all thank you for taking effort to help me. the http post is working and it is passing the correct values to the controller. but <div id="newmessage"> // style this as hidden @{ Html.RenderPartial("_posts"); } </div> this line is giving me exception because "_post" partial view needs a object of type message to be passed, it is giving me object null exception.

Also for the first message in the list, when I am adding a comment to it, it adds multiple times.

@{ Html.RenderPartial("_posts", message); }

OK, I see it now, it needs to be @{ Html.RenderPartial("_posts", new Message()); }, but you also need to make sure that in the constructor for Message you initialize the Comments - Comments = new List<Comments>(); (I don't know what your models are so I needed to make a few guesses)

Can't see why it would add multiple comments? Put breakpoints on the scripts and step through the code with the debugger to check whats happening.

javascript - Not able to refresh the partial view after a form submiss...

javascript jquery ajax asp.net-mvc razor
Rectangle 27 0

The problem is you are using a different overload of the ActionLink method than you probably want. The one you are using is taking your third parameter and using it as the route values, not the controller name. Try changing your links to this:

@Html.ActionLink("Home", "Index", "Home", new {}, new { @class = "basiclink" })

Thank you very much for the quick response. It does exactly what I need it to do now. Out of curiosity, what is the route value that I can put in there now?

Route values are used to pass something like arguments to your pages. So say you have a page that shows detailed product information (/Products/Details). You wouldn't want to make a new action and page for every product. Rather you would use a route value, like a product id, and reuse the page. You would use something like 'Html.ActionLink("Details", "Details", "Products", new { id = 10 }, new { @class = "basiclink" })' to get a link like /Products/Details/10. Then each product link would just change the route value to show the information for a different product.

Awesome. Thanks for the explanation. It's been very helpful in getting me moving forward on this application.

asp.net - Refresh RenderBody() Content with Razor Pages - Stack Overfl...

asp.net entity-framework asp.net-mvc-4 razor
Rectangle 27 0

Finally, we decided to use an old and deprecated solution, but in my particular case (screen size fixed, no mobile, support just for ff) it works very good. I use iframe html tags: creating a custom starting web page that contains 3 different iframe that call their own function controller. I don't recommend it, but may be for someone can be useful, in case of emergency like mine..

c# - ASP.NET MVC Razor - Navigate without refresh master page - Stack ...

c# asp.net-mvc razor
Rectangle 27 0

There are a few ways to handle this, one is have your partial view add a hash or querystring to the url, and have handling in your JavaScript or controller to know how to grab the hash/querystring and load the right partial view on the page reload.

But if you need to keep track of what they were doing before hitting reload, you could either use something that is holding their location server-side, or caching client-side. For tips on caching, look at this or this.

I found both work equally well, but going with the hash or querystring will show in the url, not always what you are going for.

I'm not sure what frameworks you are using on the client-side (knockout.js, jQuery, etc.) but a lot of these make this stuff easier, you could create a simple cache of your views on load, adding the needed views to the cache based on whatever order you need them, and just inject it into a div or something when they call for it.

The issue here, is that partial views are like code snippits in a way, the server knows how to dish them up, and the client knows how to view them, but the browser doesn't view them as entries into your browser history so you have to tell the browser how to ensure your data gets reloaded how you want.

Another option you could look at would be injecting them into the browser history, but you still need a way for the server to dish up the right partial on load. I found this here on a guy's implementation of loading partials for single-page web applications, seemed like a good option. But again, you need to know how you are going to dish up that data on a reload. But to answer the comment, there isn't some magical way for the browser to know what you are calling with ajax. if you want the browser to know about it automatically, try using @Html.Partial(string partialViewName) or @Html.RenderPartial(string partialViewName) see MSDN on these.

You could also look into putting something in the viewdata, tempdata, viewbag, or session data look at this article on the differences, to see if one would work for your needs.

There has to be some easier way than these. I would figure since we are up to mvc5 and razor3/4, they would have a simpler way to integrate the back and forward of partial views.

I'd suggest looking at sammy.js read a simple intro/explaination here as one of the nice things it does is allow browser navigation with a single page application - but again you use the hash in the url. - but it is easier than writing it yourself. also check my edit for other options.

javascript - ASP.net Razor Refresh on partial view returns to home pag...

javascript ajax asp.net-mvc razor
Rectangle 27 0

In controller or page load code use:

HttpContext.Cache.Insert("Record"+ recordid, 1);
Response.AddCacheItemDependency("Record"+ recordid);
HttpContext.Cache.Remove("Record"+ recordid);

asp.net mvc 3 - MVC3 razor ----> Refresh OutputCache after record dele...

asp.net-mvc-3 razor outputcache
Rectangle 27 0

What I think you are trying to do is refresh a page to reorder a list using the Razor syntax without a page refresh or HTTP call to the server. This is not possible because the View in the ASP.NET MVC world is cshtml definition which is going to execute once per call. You need something running on the client side to refresh the page (ie JavaScript).

A good idea is to output the contents of your model as Json (which you could do in a standard MVC controller (without an associated view) returning a JsonResult using the MVC controller Json function. You could also use a WebApi controller which can produce Json nativly.

You will then need to have some code on the client side to look at that model and reorder it in response to your client interactions. Angular.js and Backbone.js are good contenders for this but there are lots of others.

Right now the methodology i am using is going to controller and again fetching the same records from the existing model, reordering and putting it in View. But because the page is getting refreshed, i was asked to validate it on the view side itself. thanks for the answer. Let me have a look athe the client interaction sites and fetching the solution with the links you provided. @AlexC

c# - Sorting items in a list of MVC view without involvement of contro...

c# javascript asp.net-mvc asp.net-mvc-viewmodel asp.net-mvc-views
Rectangle 27 0

I will seize upon the term grid. I assume you have constructed some sort of grid using html/razor/javascript etc. Then you placed it in a partial view. Now you want that grid to refresh after you do an update.

I have provided a comprehensive solution to the problem of displaying data in grid format using ASP.NET MVC 3 and the jQuery-UI plugin jqGrid.

The solution is ajax based and provides full CRUD functionality. You can convert the grid into a read-only grid if needed. I have not had any issues with model values not being updated.

asp.net mvc 3 - MVC 3 : Page Model not getting updated in Partial View...

jquery asp.net-mvc-3
Rectangle 27 0

I've tried an Ajax call to the appropriate URL, but it doesn't refresh the display.

That's exactly what you should have use. Let's suppose that you have the following view:

and then you could write the following script which will send an AJAX request ti the corresponding controller action when the button is clicked and load the content in the div:

and now all that's left of course is to have the corresponding controller action that will load the data from the mainframe and render a partial view:

I'm not able to get this working. Is the button supposed to be in the parent view, or the second page which has only the partial view? I've tried both, but in neither case does my breakpoint in the controller get hit. I'll post my code shortly.

Got it working by adding the quotes, as Francisco pointed out above. Many, many thanks!

You added the quotes where? In this answer where does the url comes from?

jquery - MVC with Razor: how to refresh partial page on click? - Stack...

jquery asp.net-mvc razor
Rectangle 27 0

Every time a view is retrieved using a standard call, master view is refreshed.

If you want to avoid this, you should create all your views using PartialViews, and do AJAX calls. So, when you click a link, an ajax call is performed, the partial view is retrieved and a DOM element (usually a div) is filled with the contents of partial view.

Doing this by hand is possible but you will have to face a lot of issues. If you really want to do a SPA (Single Page Application) start looking AngularJs, Durandal, Backbone or any Javascript library that help you on this! (i. e. take a look at http://www.codeproject.com/Articles/709766/Tutorial-for-Building-SPA-using-AngularJS).

No. You can leave your master page as is. You need an initial full view (i. e. /home/index). This view will render a DOM element (i. e. a <div>) and using AJAX calls you will "fill" this div with the contents of partial views. This is basically an SPA app. For an example of doing it manually (not recommended) can look at my blog (sorry, is in spanish): geeks.ms/blogs/etomas/archive/2011/10/08/. But i rcommend you to use some library like AngularJs!

I'd like to use AngularJs, i like write js, but now it's too late because the project it's already advanced. Your solution was for sure the cleanest but not simple, thank you for help. I decided for other solution, i ll explain in answer

c# - ASP.NET MVC Razor - Navigate without refresh master page - Stack ...

c# asp.net-mvc razor
Rectangle 27 0

The issue is that the ~ is not valid html or a valid URL. But you can use the URL extension methods within Razor to translate the path for you as it understands the tilde. ASP.NET understands the ~ as the root of your application and will translate it accordingly.

<head>
    <meta http-equiv="refresh" content="3; url=@Url.Content("~/Incidents")">
</head>
<body> 
    <div>
        <p>
            <center>
                <a href="@Url.Content("~/Incidents")">View Incidents</a>
            </center>
        </p>

servicestack Razor page with relative path in meta refresh not served ...

servicestack