0

I use Ajax for calling Action and try to display returned message from Controller to the View. However, although the message is returned with TempData, it is not displayed on the View (Actually I was displaying it in @Html.BeginForm(), but this time I use <form> and maybe it is due to that). On the other hand, I tried to use jquery.cookie as explained on this page, but cannot display the message. Could you give me a sample for both TempData and jquery.cookie by showing the necessary lines on Controller and View? Thanks in advance.

View:

<form id="frmCreate"  action="Create" method="post" enctype="multipart/form-data" >

@if (TempData["message"] != null)
{
    <div class="text-danger">@TempData["message"].ToString()</div>
}
//... removed for brevity
</form>


Controller:

public ActionResult Create([Bind(Exclude = null)] PersonViewModel person)
{
    //Some stuff (removed for brevity)
    TempData["message"] = "Record has been added...";
    return PartialView("Create", person);
}


=============================== Update ===============================

View:

@model PersonViewModel

<form id="frmCreate"  action="Create" method="post" enctype="multipart/form-data" >

@Html.AntiForgeryToken()

<div class="container">

    @Html.ValidationSummary(true)

    <div><b>Message:@ViewBag.Message</b></div>

    @Html.LabelFor(m => m.ProjectID)
    @(Html.Kendo().DropDownList()
          .Name("ProjectID")
          //... removed for brevity
    )
    <br />

    @*Render Partialview according to Dropdownlists selectedIndex*@
    <!-- Place where you will insert your partial -->
    <div id="partialPlaceHolder" style="display:none;"></div>

</div>


<div class="modal-footer">
    @(Html.Kendo().Button().Name("btnCancel"))

    @(Html.Kendo().Button().Name("btnSubmit"))
        .HtmlAttributes(new { type = "submit"})
</div>

</form>



<script type="text/javascript">

//OnLoad method & functions::::::::::
$(function () {      
    var selectedProjectId = $('#ProjectID').val(); /* Get the selected value of dropdownlist */       
    var json = JSON.stringify(@Model);
    $.ajax({
        type: "POST",
        url: '@Url.Action("RenderPartialView", "Person")' + selectedProjectId,
        contentType: "application/json; charset=utf-8",
        data: json,
        dataType: "json",
        success: function (data) {
            // get the result and do some magic with it
            var message = data.Message;
            $("#resultMessage").html(message);
        }
    });


});


//For keeping model values we use <form> instead of Html.BeginForm()
$('form').submit(function (event) {
    event.preventDefault();
    $.post('Person/Create', $(this).serialize()).done(function () {

    }).fail(function () {

    });
});

//Render Partialview according to Dropdownlist's selectedIndex
$('#ProjectID').change(function () {  
    var selectedProjectId = $(this).val();
    $.get('/Person/RenderPartialView/' + selectedProjectId, function (data) {
        $('#partialPlaceHolder').html(data);
    });        
});

</script>
Community
  • 1
  • 1
Jack
  • 1
  • 21
  • 118
  • 236
  • Question : what's the point of returning a partial-view. Why not return a JSON object with a result parameter of success or failure? – PaulBinder Jun 17 '15 at 21:07
  • I call the partialview inside the view. But, the problem is on the view, because view is rendered first and TempData["message"] should be displayed before partialview is called. Is that true? Regarding to return type, I have used some controller methods returning JSon, but they are related to list and I do not know which changes should be made on my controller action in order to return JSon. Could you give an example for simply return JSon? Thanks in advance. – Jack Jun 17 '15 at 21:12
  • @PaulBinder Actually when using TempData or ViewBag, the message is seen in the response on Firebug, but it is not displayed. Any idea? – Jack Jun 17 '15 at 21:29
  • How are you using `Ajax`? You need to show the script. But in any case, `TempData` is not the correct usage here (which is for passing data between requests). Using `ViewBag` would be more appropriate. –  Jun 18 '15 at 00:37
  • @StephenMuecke I added the view code to the question. I also used with viewbag but although it seems in the response, it cannot be rendered. I think it may be gone during calling partialview from view. – Jack Jun 18 '15 at 06:24
  • You said you using ajax - but you have not shown the script –  Jun 18 '15 at 06:26
  • @StephenMuecke I added now. Sorry, I did not think of that you were so fast :) – Jack Jun 18 '15 at 06:28
  • I'm a bit confused - you have show 3 ajax calls (only one seems relevant to the question so you should delete the others). None of them call the `Create()` method you have shown. The closest one is `$.post('Issue/_Create', ....` but that does nothing anyway –  Jun 18 '15 at 06:40
  • I updated the code. Yes, the post method is `$.post('Person/Create', $(this).serialize()).done(function ()` line. – Jack Jun 18 '15 at 06:55
  • Now you have deleted all the scripts :) –  Jun 18 '15 at 06:59
  • No, I did not, I just updated :( On the other hand, I used to pass data with TempData in my previous project. As you said, I should use ViewBag, however it did not make any sense. I think the viewbag message returns to the view, but after calling partial view it is gone. What do you think? – Jack Jun 18 '15 at 07:06
  • @Christof, Still a bit unsure what your doing. Your `$.post('Person/Create', $(this).serialize()`..` method might hit the method and return some html, but you never do anything with it. But since the method would just return exactly the same view (with the message) it would be better to just return the message as json and update the DOM –  Jun 18 '15 at 07:20
  • Sorry, I have no experience with Ajax and Javascript. Could you post the corrected sample as an answer? Thanks in advance. – Jack Jun 18 '15 at 07:22
  • @Christof, Well you are doing something similar in your first script (// OnLoad method & functions ...) but that one is also a bit strange :). Are you wanting to display the message returned by the `Create()` method in the element with `id="ResultMessage"`? - and please start you message as I have done with this one so I get a notification :) –  Jun 18 '15 at 07:41
  • I forgot to remove ResultMessage. What I do and want to do are: 1) I call a partialview when selectedProjectId changed (dropdownlist) and form loaded. 2) I call the action in the controller by using Ajax and return View and message. On the other hand, it is ok to return Json. 3) I tried to use Html.BeginForm() and Ajax.BeginForm(), but it was not possible and I have to use
    and Ajax call. So, could you please provide a solution having AjaxCall and a controller method returning the view and TempData / ViewBag message. Could you help please? Thanks in advance.
    – Jack Jun 18 '15 at 08:00
  • @StephenMuecke Any reply please? – Jack Jun 18 '15 at 08:22
  • @StephenMuecke When using Ajax, I cannot upload files that I had managed with the Html.BeginForm(). Any idea? – Jack Jun 18 '15 at 08:25
  • I will reply, but you forgot to notify me :). Need a break so will have a look a little later. –  Jun 18 '15 at 08:26
  • @StephenMuecke:Many thanks for your helps. Actually I used to `@Html.BeginForm()` in my projects before and after using `Ajax`, there is not only `TempData` problem, also `File Upload` problem I have encountered. Therefore, if it is better to use `@Html.BeginForm()`, do not spend your time to solve this problem. Instead of this, you have a look at [Why PartialView cannot reload with Ajax in MVC](http://stackoverflow.com/questions/30868493/why-partialview-cannot-reload-with-ajax-in-mvc) >>> – Jack Jun 18 '15 at 08:36
  • >>> Because, I would use `@Html.BeginForm` if I solved that problem. The only thing I need, to keep the Model values after submitting the form and returning back to the View. It would be much more better to solve that issue. Could you help on [that](http://stackoverflow.com/questions/30868493/why-partialview-cannot-reload-with-ajax-in-mvc) issue please? Thanks in advance. – Jack Jun 18 '15 at 08:36
  • @Christof, You have marked that answer as accepted so I assume your issues are solved. But you mentioned you could not upload files with ajax - you can. Refer [this answer](http://stackoverflow.com/questions/29293637/how-to-append-whole-set-of-model-to-formdata-and-obtain-it-in-mvc/29293681#29293681) –  Jun 19 '15 at 01:56
  • @StephenMuecke Yes, I have managed to reload the popup window with model data by using Ajax. However, at that time I faced a new problem regarding to file attachment as it is not suitable with Ajax as I see the answer on stackoverflow. So, I changed my structure and decided to use @Html.BeginForm() again (I left popup vindow and use view in a page). For this time I faced to reload the partialview again (I have a view and there is a ProjectID dropdownlist. >>> – Jack Jun 19 '15 at 06:53
  • @StephenMuecke >>> When changing dropdownlist, the partialview is rendered in the view. I also call the related javascript method when form load, however the partialview is not rendered when form returning from controller :( My question is that: Would it be possible to reload partialview when it returns from controller with @Html.BeginForm() and without Ajax? If not, there is no problem and I will use a new view for ProjectID dropdownlist and pass it's value to the other Create view (I use Next button after user select ProjectID dropdownlist) then open the new View. Any suggestion please? – Jack Jun 19 '15 at 06:56

0 Answers0