Category Archives: Table

Table

[RESOLVED]Mock Response.Cookies.Add(…) in MVC unit testing

The basic problem is that the controller I’m testing calls Response.Cookies.Add(…) but since the unit test is not in an HTTPContext, Response is null and I get an exception. Can someone give me an example. ?

Look at hanselmann 

http://www.hanselman.com/blog/ABackToBasicsCaseStudyImplementingHTTPFileUploadWithASPNETMVCIncludingTestsAndMocks.aspx

how it mocks Request and Request.Files

Same way you will mock Request and Request.Cookies

You have to abstract access to non-testable resources like cookies.  Create an interface and a class that implements your interface

namespace TestMvc.Managers
{
    public interface IClientStorageManager
    {
        void Store(string key, string value);
    }
}

namespace TestMvc.Managers
{
    public class CookieStorageManager : IClientStorageManager
    {
        public void Store(string key, string value)
        {
            HttpCookie c = new HttpCookie(key);
            c.Value = value;

            System.Web.HttpContext.Current.Response.Cookies.Add(c);
        }
    }
}

Use this rather than accessing cookies direct

public class HomeController : Controller
{
    private IClientStorageManager clientStorageManager;

    public HomeController()
        : this(new CookieStorageManager())
    {
        // you can use DI to do this instead
    }

    public HomeController(IClientStorageManager clientStorageManager)
    {
        this.clientStorageManager = clientStorageManager;
    }

    public ActionResult Index(string name = null)
    {
        this.clientStorageManager.Store("name", name);

        return View();
    }

You can now mock the storage class from your unit test

[TestClass]
public class UnitTest1
{
    [TestMethod]
    public void TestMethod1()
    {
        // I'm using moq, but you can use any mocking framework you want, or even self-shunting
        Mock<IClientStorageManager> storage = new Mock<IClientStorageManager>();

        HomeController c = new HomeController(storage.Object);

        c.Index("Bob");

        storage.Verify(s => s.Store(It.IsAny<string>(), "Bob"), Times.AtLeastOnce());
    }
}

[RESOLVED]How to pass records between Views?

I have a table of records and a submit button.
How do i Pass those records from one view to another another view while clicking the Submit Button?

Thanks in advance!

From the view, the data goes to the respective controller. That’s the route. From that controller you can server your desired view and pass the data to it as model object.

Using the following in the controller action method:

return View("AnotherView",ModelObject);

How did your table initially populate with records?  Action and View code would be useful

Do you mean view to view or from one controller to another controller? What I get from the question is that on submit you will be calling another page/controller?

If it is controller to another controller then use tempdata. 

How to pass data in ASP.Net MVC app refer below

http://msdn.microsoft.com/en-in/library/dd394711(v=vs.100).aspx

there is no direct passing of data between views. a view is html that is returned to the browser. when that view contains an anchor (link) to request a new html page, data can be passed via the query string. if its a form submit, then the form fields are
passed. MVC’s data binder will bind these field to the action parameters (often a model).

so to pass data from one form to another usually requires a form, and submit. all data must be in a <input>, <select> or <textarea>. to pass a complete object, each property must be written to a form field, or that property will not be in the postback data
(which is a name/value collection).

if you are writing a javascript application, then there are more ways to pass data via ajax or dynamic forms, but thats different

You cannot pass data directly from view to another view on submit

you submit data to action and action returns the view by passing the data

Can you give me any sample code on how to pass list of records from one table to another table?

from html table to html table?

or

db table to db table?

From HTML table to another HTML table

check this

<table id="table1" border="1">
    <tr> <td>ID</td> <td>Name</td></tr>
    <tr> <td>1</td><td>Name1</td> <td><input type="checkbox" id="movebutton" value="Move" onclick="MoveRow(this)" /></td> </tr>
    <tr> <td>2</td><td>Name2</td> <td><input type="checkbox" id="movebutton" value="Move" onclick="MoveRow(this)" /></td> </tr>
    <tr> <td>3</td><td>Name3</td> <td><input type="checkbox" id="movebutton" value="Move" onclick="MoveRow(this)" /></td> </tr>
    <tr> <td>4</td><td>Name4</td> <td><input type="checkbox" id="movebutton" value="Move" onclick="MoveRow(this)" /></td> </tr>
</table>
<br />
<br />
<br />
<table id="table2" border="1"><tr> <td>1</td><td>Name1</td> <td></td></table>

    <script>
        function MoveRow(movebutton) {
            var table2 = document.getElementById("table1");
            var table2 = document.getElementById("table2");
            var rowchecked = movebutton.parentNode.parentNode;
            var rowcheckedClone = rowchecked.cloneNode(true);
            var checked = movebutton.checked;
            var foundIndex = -1;
            rowcheckedClone.deleteCell(0);
            rowcheckedClone.deleteCell(1);

            for (var i = 0; i < table2.rows.length; i++) {
                if (rowcheckedClone.isEqualNode(table2.rows[i])) {
                    foundIndex = i;
                }
            }
            if (checked) {
                if (foundIndex == -1)
                    table2.appendChild(rowcheckedClone);
            }
            else {
                if (foundIndex > -1)
                    table2.deleteRow(foundIndex);
            }
        }
    </script>

[RESOLVED]MVC 4 generate ViewModel from multiple tables

I want to generate ViewModel (contains Teacher Name and list of student’s Names) from multiple tables. Teachers table and Student table.

   Teacher’s model contains  public virtual ICollection<Student> Students { get; set; }

var model = (from x in db.Teachers where x.Email = email select new TeacherVM { Name = x.Name, StudentNames = x.Student.ToList() }).FirstOrDefault()

How do I retrieve all students into the TeacherVM in a format ("Bob","Mike","Dan")

Thanks,

Can you post your Teacher and Student models?

 public class Teachers
    {
        public int Id { get; set; }
        public string Name { get; set; }
        public string Email { get; set; }
        public virtual ICollection<Student> Students { get; set; }
      …..
   }

    public class Student
    {
        public int Id { get; set; }
        public string Name{ get; set; }
        public virtual ICollection<Teachers> Teachers{ get; set; }
        …..
    }

And you want to list all students assigned to a specific teacher?  Or you just want to list all teachers and all students?

all students assigned to a specific teacher

so the viewmodel would contain 2 fields Teacher Name and list of all students

I tried this but I think I am missing something.

var model = (from x in db.Teachers where x.Email = email select new TeacherVM { Name = x.Name, StudentNames = x.Student.ToList() }).FirstOrDefault()

In the view I want to display 2 textboxes first textbox "Teacher Name" and another textbox all students comma separated
Bob,Mike,Dan

Thanks,

Do you have a relationship mapping between Teacher and Student?  Typically when you have a many-to-many relationship schema, you need a 3rd class/model/table that maps the relationship between those tables.  With your current two tables, you don’t have any
way of knowing which student belongs to which teacher, and vice versa.

Example:

public class Enrollment
{
  public int EnrollmentID { get; set; }
  public int TeacherID { get; set; }
  public int StudentID { get; set; }
}

and then you’d need primary keys in your Teacher and Student tables:

    public class Teachers
    {
        public int TeacherID { get; set; }
        public string Name { get; set; }
        public string Email { get; set; }
        public virtual ICollection<Enrollment> Enrollments { get; set; }
      .....
    }

    public class Student
    {
        public int StudentID { get; set; }
        public string Name{ get; set; }
        public virtual ICollection<Enrollment> Enrollments{ get; set; }
        .....
    }

Your Enrollments table would then have data like this:

EnrollmentID TeacherID StudentID
1 1 2
2 1 3
3 2 1
4 2 3

As you can see in the table above, Teacher #1 has Students #2 and #3, while Teacher #2 has Students #1 and #3.  Student #3 has teachers #1 and #2.  This is critical information that we need to have for many-to-many relationships.

Once you have this schema, you can create your Teacher-Students list

Teacher Details action:

public ActionResult TeacherDetails(int id)
{
  var teacher = db.Teachers.Find(id);

  return View(teacher);
}

View:

@model AppName.Models.Teacher

Teacher Name: @Model.Name
Teacher Email: @Model.Email

<h3>Students assigned to Teacher</h3>

@foreach (var item in Model.Enrollments)
{
  @Html.DisplayFor(modelItem => item.Student.Name) <br />
}

And that’s it.  Pretty standard solution for many-to-many relationships.

Thanks John for the explanation all makes sense. I was wondering instead of 

  var teacher = db.Teachers.Find(id);

to add teacher’s record and the student names into viewmodel in the controller

 public class TeacherVM 
    {
       public string Name { get; set; }
       public string StudentNames { get; set; } 
    }

something like this:

var model = (from x in db.Teachers 
             where x.Email = email 
             select new TeacherVM { 
                Name = x.Name,
                StudentNames = ??  <-- not sure how to get the list
             }).FirstOrDefault()
return View("teacher", model)

and then pass the viewmodel into the view so instead of doing a foreach to retrieve each single student.name I would just pass a string that would contain 
Bob,Mike,Dan into the textbox so the that the teacher can update the textbox right away instead of having edit button and another page. I hope it makes sense what I want to do. thanks for your help!

Sorry for the delayed response.  Let’s take a look at why you can’t do it the way you want to.

Yes, you could totally use a view model if you wanted, however you still need a relationship mapping between teacher(s) and student(s).  This is why I suggested a 3rd table (Enrollments) to establish which student has which teacher, and vice versa.

StudentNames = ??  <-- not sure how to get the list

With your current solution (Teacher and Student tables only), you have no way of getting this list.  There’s no association between the two.  Hence, you need that Enrollments table.  If you had that table, you could do something like this:

var teacher = db.Teachers.Single(t => t.Email == email);
var students = db.Students.Where(s => s.Enrollments.TeacherID == teacher.TeacherID); var model = new TeacherVM(); model.Name = teacher.Name; model.StudentNames = string.Join(",", students); return View(model);

As you can see, we use the Enrollments model to track down the students that have the teacher’s ID associated to their record in the Enrollments table.  How ever you want to handle this solution, you need to have a table that manages your many-to-many relationships.

You are absolutely correct. Sorry it took me a while to get this, new to mvc. But you made it all clear. Appreciate your help.

[RESOLVED]fast paging for large numbers of data

which is the easy way to create fast paging for large amount of data more than 10 thousand

tried out ajax paging but taking too much time

nuget paged list fetch all the data which makes the site slow

now how to do the paging please suggest

plus it has a search form i want a paging which maintain search result for it

Hi,

For large amount of data, we need to make paging at the server side. You may see

http://www.asp.net/mvc/tutorials/getting-started-with-ef-5-using-mvc-4/sorting-filtering-and-paging-with-the-entity-framework-in-an-asp-net-mvc-application.

It may help.

Have fun

How many records do you show in 1 page? You need to get only that many records from the DB. Refer below link for DB paging 

http://social.technet.microsoft.com/wiki/contents/articles/23811.paging-a-query-with-sql-server.aspx 

How many records retrieving from db

If you are getting all 10000 from db and handling front-end the here is my idea.

1. Define a store proc in the back to return only the specific page records and count variable

   search proc should have pagesize, pageindex, sort,sortdir, totalcount out and other search parameters

2. So you get only the particular page records from procedure with total_record_count as out

3. Map the page records (returned by store proc) to a model list

4. Send model list to web grid

5. Design asp.net mvc web grid with this result model list and use webgrid.bind method where you can total_record_count) to let the webgrid to render paging

Try DataTables JQuery control. This is free and has a option to fetch page by page using ajax. I used it earlier and worked well. Please see this blog for more information

jQuery
DataTables and ASP.NET
MVC
Integration – Part I

[RESOLVED]List<string> passed in ViewBag gets with “System.Collections.Generic.List`1[System.String]”

I have a link to another controller and I want to pass a list of strings.

FirstController.cs

I have list of records in table with checkbox in each row, List of string values are selected by checking the checkbox.

public ActionResult Select(bool isChecked, String id)
        {
            var selectList = (List<String>)HttpContext.Session["SelectList"] ?? new List<String>();
            if (isChecked && !selectList.Contains(id))
            {
                selectList.Add(id);
            }
            else if (!isChecked && selectList.Contains(id))
            {
                selectList.RemoveAll(s => s == id);
            }
            ViewBag.selectList = selectList;
            return Content("OK");
        }

This list of string values i am passing to another SecondController.cs using ‘ViewBag’

public ActionResult AddSitesToUser(string returnUrl,string selectList, int userId = 0)
        {
            ViewBag.selectList = selectList;
}

My View:

(Html.BeginForm("AddSitesToUser", "User", new { returnUrl = ViewBag.returnUrl,selectList=((List<string>)ViewBag.selectList )})

In my FirstController.cs the list of ViewBag.selectList = selectList; created properly, but if i pass those list of strings to SecondController.cs instead of returning list of strings it gives me ‘"System.Collections.Generic.List1[System.String]"

Any idea on what I’m doing wrong?

Thanks

This is because you are using this within the RouteValues parameter of the BeginForm() method, which will populate QueryString variables for the action attribute on the Form itself.

If you are storing a collection of strings within the ViewBag, ASP.NET isn’t going to know how to display this within the URL so it uses "System.Collections.Generic.List" as it was passed a string and that’s the only way it knows how to interpret it.

You might try storing a comma-delimited string within ViewBag which might be able to be passed along more easily as follows :

// When storing your values in the SelectList, consider using a comma-delimited string (e.g. "A,B,C,D,E,F")
ViewBag.selectList = String.Join(",",selectList.Items.Cast<string>().ToArray());

This will add this comma-delimited string to your form properly when it loads your selectList variable : 

(Html.BeginForm("AddSitesToUser", "User", new { returnUrl = ViewBag.returnUrl,selectList=ViewBag.selectList )})

Then when your AddSitesToUser method is posted to, you can pull your collection out of the QueryString and properly split it back into a collection :

public ActionResult AddSitesToUser(string returnUrl,string selectList, int userId = 0)
{
     // Retrieve your list
     List<string> list = selectList.Split(',').ToList();
}

Tried with your solution, but still showing same 

“System.Collections.Generic.List`1[System.String]”

That’s shouldn’t be happening, as the line where you actually set your ViewBag should store a string into it (and not a collection) :

ViewBag.selectList = String.Join(",",selectList.Items.Cast<string>().ToArray());

when you add routes values to the form, ToString() is called on the value to make it a string. for List<> (and most classes). the to string just returns the class name. you need to convert the list to a string value, that your controller can later parse.

[RESOLVED]How to display a default value in Cascading DropDownList using Java Script and MVC4

I have 2 Cascading DropDownLists (State and Cities) .

I populate cities when I select a State.

In the Cities Dropdown list, the default value is not displayed but all the related Cities are displayed.

Can someone please help to populate a default value in Cities Dropdown list?

The following is my model for State and Cities DropDown list

public class AustraliaStates
    {
        [Key]
        [Required]
        public string AustraliaStateId { get; set; }
        [Required]
        public string AustraliaStateName { get; set; }
    }

    public class AustraliaCities
    {
        [Key]
        [Required]
        public string AustraliaCityId { get; set; }

        [Required]
        public string AustraliaCityName { get; set; }
        
        [Required]
        public string AustraliaStateId { get; set; }
        
    }

Accommodation View.cshtml

      <form name="datapluspics" method="post" enctype="multipart/form-data">
                    @Html.ValidationSummary(true)
                    <fieldset>
                    @*Form Display Table START here*@
                    <table class="FormTableStyle" >
                                                
                        <tr>
                            <td class="FormDisplayLeftTableStyle">
                                <div class="editor-label">
                                    @Html.LabelFor(model => model.Suburb)
                                </div>
                            </td>
                            <td class="FormDisplayRightTableStyle">
                                <div class="editor-field">
                                    : @Html.EditorFor(model => model.Suburb)
                                    @Html.ValidationMessageFor(model => model.Suburb)
                                </div>
                            </td>    
                        </tr>

                        <tr>
                            <td class="FormDisplayLeftTableStyle">
                                <div class="editor-label">
                                    @Html.LabelFor(model => model.State)
                                </div>
                            </td>

                            <td class="FormDisplayRightTableStyle">
                                <div class="editor-field">
                                            <div>
                                             : @Html.DropDownListFor(model => model.SelectedAustraliaStateId, Model.AustraliaStates, "Select a state", new { id = "States", @class = "DropDownFieldStyle" })
                                             @Html.ValidationMessageFor(model => model.SelectedAustraliaStateId)
                                </div>
                            </td>    
                        </tr>

                        <tr>
                            <td class="FormDisplayLeftTableStyle">
                                <div class="editor-label">
                                    @Html.LabelFor(model => model.City)
                                </div>
                            </td>
                            <td class="FormDisplayRightTableStyle">
                                <div class="editor-field">
                                    : @Html.DropDownListFor(model => model.SelectedAustraliaCityId, Model.AustraliaCities, "Select a City", new { id = "Cities", @class = "DropDownFieldStyle" })
                                </div>
                            </td>    
                        </tr>

</table> 
                    </fieldset>
                    @*Form Display Table END here*@
                
                </form>

Here is the JS script

@section Scripts {

                    <script type="text/javascript">
                        $("#Cities").hide();

                        $("#States").on("change", function () {

                            var cityDropdown = $('#Cities');
                            cityDropdown.empty();

                            $.getJSON('@Url.Action("GetCities")',
                            { id: $(this).val() },
                            function (cities) 
                            {
                                $.each(cities, function (i, city) 
                                {
                                    $("#Cities").append('<option value="' + city.AustraliaCityId + '">' + city.AustraliaCityName + '</option>');
                                });

                            });


                            $('#Cities').show();

                        });
                    </script>

                }

GetCities Action in Controller:

[HttpGet]
        public ActionResult GetCities(string id)
        {
            var cities = db.AustraliaCities.Where(c => c.AustraliaStateId == id).ToList();

            return Json(cities, JsonRequestBehavior.AllowGet);
        }

Can someone please help me?

Here is my site: http://overseasindians.com.au/

@section Scripts {

                    <script type="text/javascript">
                        $("#Cities").hide();

                        $("#States").on("change", function () {

                            var $cityDropdown = $('#Cities');
                            $cityDropdown.empty();

                            $.getJSON('@Url.Action("GetCities")',
                            { id: $(this).val() },
                            function (cities) 
                            {
                                $cityDropdown.append('<option value="">Select One...</option>').val("");
                                $.each(cities, function (i, city) 
                                {
                                    $cityDropdown.append('<option value="' + city.AustraliaCityId + '">' + city.AustraliaCityName + '</option>');
                                });

                            });


                            $cityDropdown.show();

                        });
                    </script>

                }

Hope this helps. it’s not tested, but you should catch the idea.

[RESOLVED]Table in partial view being replaced with table containing old non-current data

I have a view which we will call Create.cshtml.  On this view there is a call to a partial view called _PurchaseRequestTable.cshtml, using RenderAction, which calls a separate action on the controller called PurchaseRequestTable which returns a partial view.

Now I have two buttons on the form one for creating the record in the database and the other for updating the record on the databases.  Now when the onclick event handler for the each button runs, first an Ajax call is made to a function to interact with
the database, and then an Ajax call is made to the PurchaseRequestTable action to rebuild the partial view and replace the contents of the div rendered in the partial view with the new return from the action.

However what is happenning is that when the buttons are clicked, the new data is properly saved to the database, but when the partial view is replaced in it showing the old data.

Here is the code for the RenderAction and the controller action

@using (Html.BeginForm(null,null, FormMethod.Post, new { id = "PRCreate" })) {
    @Html.AntiForgeryToken()
    @Html.ValidationSummary(true)

    <fieldset>
        <legend>Add Purchase Requests</legend>
        <div id="overlay" style="position: fixed;top: 0;right: 0;bottom: 0;left: 0;height: 100%;width: 100%;margin: 0;padding: 0;background: #000000;opacity: .15;filter: alpha(opacity=15);-moz-opacity: .15;z-index: 101;display: none;" >

        </div>


        @{ Int32 prID = 0;
            if (Model.PurchaseRequest != null)
            {
                prID = Model.PurchaseRequest.PRID;
            }
            Html.RenderAction("PurchaseRequestTable", new { id = prID });
           }
 
        <br />
        <br />
        <br />
                          ....
        public ActionResult PurchaseRequestTable(Int32 id = 0)
        {
            using (var db = new VFS_ProcurementTrackEntities(Session["csProcTrack"].ToString()))  //breakpoint added here*****
            {
                ViewBag.PRID = id;
                var PR = new PurchaseRequestTableModel();



                if (id != 0)
                {
                    var currentRequest = db.prc_PRs.Find(id);
                    PR.PurchaseRequest = currentRequest;

                }
                else
                {
                    DateTime value = DateTime.Today; // Convert.ToDateTime("01/01/" + DateTime.Today.Year.ToString());
                    PR.PurchaseRequest = new prc_PRs();
                    PR.PurchaseRequest.PRID = 0;
                    PR.PurchaseRequest.PROriginatorUserRecID = (int)Session["UserRecID"];
                    PR.PurchaseRequest.PRDateCreated = value;
                }

                int defaultValue = (int)Session["UserRecID"];
                var AMSList = db.AMSList_get(0).ToList();
                SelectList amsDDList = new SelectList(AMSList, "AMSID", "AMS" , id == 0 ? defaultValue : PR.PurchaseRequest.PROriginatorUserRecID);


                PR.DDAMS = amsDDList;
                return PartialView("_PurchaseRequestTable", PR);
            }
        }

And here is the code for one of the click events being called.

   $(function () {
        //alert("created function");
        var UpdatePRs = function () {
            //alert("called function");
            //debugger
            var sURL = '@Url.Action("UpdatePurchaseRequest", "AJAXFunctions")';
            var goURLid = $("#PurchaseRequest_PRID").val();
            var form = $("#PRCreate");
            var bError = false;
            var returnedInfo = '';
            var sResultMessage = '';

            //alert(options.url);
            $.ajax({
                url: sURL,
                type: 'POST',
                data: form.serialize(),
                cache: false,
                async: false,
                dataType: 'json',
                //contentType: 'application/json; charset=utf-8',
                success: function (data) {
                    ////debugger
                    if (data != null) {
                        $(data).each(function () {
                            returnedInfo = data;
                        });
                    }
                    else {
                        returnedInfo = "Nothing was returned";
                        bError = true;
                    }
                },
                error: function () {
                    sResultMessage = 'An Error has occurred, and the changes to the PR Information were not saved.';
                    bError = true;
                }
            });
            //debugger
            //if (!bError) {
            var sURLRepost = '/PR/PurchaseRequestTable' + '/' + goURLid;
            //var options = 
            //};
            //alert(options.url);
            $.ajax({
                url: sURLRepost,
                type: "get",
                async: false,
                dataType:"html",
                success: function (data) {
                    //debugger
                    if (data != null) {
    //this is where the ajax call returns information showing the data prior to being changed. 
//break point in action is not hit. $("#PRtableView").replaceWith(data); } else { sResultMessage = "An Error has occured and no information was returned"; } }, error: function () { sResultMessage = 'An Error has occurred, and no data returned'; } }); if (!bError) { sResultMessage = "Your Edit has been completed. The changes were saved to the database."; $("#PRCreated").text(sResultMessage).toggle(); } else { sResultMessage = "Your edit was not completed. " + returnedInfo; $("#PRCreated").text(sResultMessage).toggle(); } }; $('#btnEditPR').on('click', UpdatePRs); });

On another thread with a similar problem where the Aijax call was returning a cached version of the action result Starain chen had me add a decoration to the Action like this:

 [OutputCache(NoStore = true, Duration = 0, VaryByParam = "None")]
        public ActionResult Index(int id = 0)
        {
            if (!Request.IsAjaxRequest())
            {
                id = (int)Session["UserRecID"];
            }
             ViewBag.UserID = (int)Session["UserRecID"];
             using (var db = new VFS_ProcurementTrackEntities(Session["csProcTrack"].ToString()))
             {
             //var db = new VFS_ProcurementTrackEntities(Session["csProcTrack"].ToString());
                 var model = (from pr in db.PurchaseRequests_Get_All(id)
                             orderby pr.PR_Number descending
                             select pr).ToList();
                 if (Request.IsAjaxRequest())
                 {
                     return PartialView("_PurchaseRequestsGrid", model);
                 }

                 return View(model);
             }
        }

And that resolved all of my issues.  However when I tried to do the same for the offending action here first I got "Duration must be a positive number and then when I arbitarily set it to 1 then it said that you could not use the parameter "NoStore = true"
on a on a child action.

At this point I was baffled, and asked for advice and it was suggested I start a new thread here.

So if anyone has any ideas then please let me know.

joeller

However what is happenning is that when the buttons are clicked, the new data is properly saved to the database, but when the partial view is replaced in it showing the old data.

Hi joeller,

Thanks for your post.

With your description and code provided, I see you want to update records with ajax call update action.

Then update the UI with ajax call the partial view render action. For the second ajax request always the old

content returned to, I think is the cache caused your problem. Please disable the cache of the second ajax like below:

 
            $.ajax({
                url: sURLRepost,
                type: "get",
                async: false,
                cache: false, 
                dataType:"html",
                success: function (data) {
                   
                  ................

Hope this helps, thanks.

Best Regards!

Fuxiang Zhang – MSFT

Please disable the cache of the second ajax like below:

OK that did it.  as the OP stated I tried to do that with an attribute added to the server side function but was not able to.  It totally slipped my mind that thiscould be done client side.

Thanks loads.  This wa driving me crazy.

[RESOLVED]Can I use the latest version of TinyMce with mvc5?

I guess the subjects says it all but has anyone done this and if so is there a tutorial anywhere?

Cheers,

Mike.

tinymce is strictly  client side. Its works with any server code. see the tutorials on their site. server side it just a textarea.

  @Html.TextArea("nameOfField")

be sure to add [AllowHtml] to the post back model field.

Yes but I need to use @Html.EditorFor to populate the TextArea with the data in an Edit view.

As Bruce mentions, the TinyMCE Editor is purely client-side and has nothing to do with MVC specifically. You should be able to use it as long as you have any fields that generate a <textarea> element.

It should be noted that you don’t have to use an Html.EditorFor() helper to populate your element. You could explicitly use the Html.TextAreaFor() to ensure that an actual <textarea> element is rendered and then apply the appropriate client-side code to
initialize the TinyMCE.

Complete Example

  1. Create an Project that targets MVC 5.
  2. Add the latest TinyMCE Package via NuGet (Right-click Solution > Manage NuGet Packages > Search for "TinyMCE" > Install the first "TinyMCE" package that appears).
  3. Create an Example Controller with a class that will be equivalent to your Model as seen below :
    public class TinyMCEController : Controller
    {
            // An action to display your TinyMCE editor
            public ActionResult Index()
            {
                return View();
            }
    
            // An action that will accept your Html Content
            [HttpPost]
            public ActionResult Index(ExampleClass model)
            {
                return View();
            }
    }
    
    // An example class to store your values
    public class ExampleClass
    {
            // This attributes allows your HTML Content to be sent up
            [AllowHtml]
            public string HtmlContent { get; set; } 
    
            public ExampleClass()
            {
    
            }
    }
  4. Create a View that will wire up your TinyMCE Editor and will contain the necessary code to post your HTML content :
    <!-- This View uses your Model -->
    @model TinyMCE.Controllers.ExampleClass
    <!DOCTYPE html>
    <html>
    <head>
        <meta name="viewport" content="width=device-width" />
        <title>TinyMCE Example</title>
        <!-- TinyMCE Script Reference -->
        <script src="~/scripts/tinymce/tinymce.min.js"></script>
        <!-- Script to wire up your TinyMCE editor -->
        <script type="text/javascript">
            // Initialize your tinyMCE Editor with your preferred options
            tinyMCE.init({
                // General options
                mode: "textareas",
                theme: "modern",
                // Theme options
                theme_advanced_buttons1: "save,newdocument,|,bold,italic,underline,strikethrough,|,justifyleft,justifycenter,justifyright,justifyfull,|,styleselect,formatselect,fontselect,fontsizeselect",
                theme_advanced_buttons2: "cut,copy,paste,pastetext,pasteword,|,search,replace,|,bullist,numlist,|,outdent,indent,blockquote,|,undo,redo,|,link,unlink,anchor,image,cleanup,help,code,|,insertdate,inserttime,preview,|,forecolor,backcolor",
                theme_advanced_buttons3: "tablecontrols,|,hr,removeformat,visualaid,|,sub,sup,|,charmap,emotions,iespell,media,advhr,|,print,|,ltr,rtl,|,fullscreen",
                theme_advanced_buttons4: "insertlayer,moveforward,movebackward,absolute,|,styleprops,spellchecker,|,cite,abbr,acronym,del,ins,attribs,|,visualchars,nonbreaking,template,blockquote,pagebreak,|,insertfile,insertimage",
                theme_advanced_toolbar_location: "top",
                theme_advanced_toolbar_align: "left",
                theme_advanced_statusbar_location: "bottom",
                theme_advanced_resizing: true,
    
                // Example content CSS (should be your site CSS)
                content_css: "css/example.css",
            });
        </script>
    </head>
    <body>
        <!-- This will automatically post to your Index method (that is decorated with a HttpPost attribute) -->
        @using (Html.BeginForm()) 
        {
            @Html.AntiForgeryToken()
            <div>
                <!-- This will contain your HtmlContent and use the TinyMCE editor-->
                @Html.TextAreaFor(model => model.HtmlContent)
               
                <input type="submit" value="Create" />
            </div>
        }
    </body>
    </html>
  5. Now if you navigate to your Index Action, you should see the following :
  6. And then if you Submit it, you should see your HTML Content available in your Controller :

This should be all you need to wire everything up.

Thanks Rion,

That was easier than installing the MVC version Smile

Cheers,

Mike