Tag Archives: HTML

[RESOLVED]Re-using the same model, same controller with different views

I didn’t think that this was going to cause me so much difficulty .. and I have only just started with this project Surprised

I have one model which I want to populate the model’s properties over multiple views. I was planning on using the controller to determine which View should be displayed.

The model looks like this:

public class QC_Rework
{
    public int nViewToDisplay { get; set; }
    public int nReworkNumber { get; set; }
    public string cSecondaryReferenceType { get; set; }
    public string cSecondaryReferenceNumber { get; set; }
    public int nLineQuantity { get; set; }
}

My "Create" controller looks like this:

[HttpGet]
public ActionResult Create([Bind(Prefix = "ReworkNumber")] int ReworkNumber=0)
{

    var oQC = new QC_Rework();
    oQC.nReworkNumber = ReworkNumber;
    oQC.nViewToDisplay = 1;
    return View("GetSecondaryReferenceType2", oQC);

}

[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult Create(QC_Rework oQC_Rework)
{
    // After GetSecondaryReferenceNumber2 the value of nViewToDisplay is "1"!!!
    // Even though the value in the Source Code and in the form says "2"!!!
    if (ModelState.IsValid)
    {
        switch (oQC_Rework.nViewToDisplay)
        {
            // Coming from Secondary Reference Type View
            case 1:
                if (String.IsNullOrEmpty(oQC_Rework.cSecondaryReferenceType) == true)
                {
                    ModelState.AddModelError("Model", "A secondary reference type needs to be selected!");
                    return View("GetSecondaryReferenceType2", oQC_Rework);
                }
                else
                {
                    oQC_Rework.nViewToDisplay = 2;
                    return View("GetSecondaryReferenceNumber2", oQC_Rework);

                }
            // Coming from Secondary Reference Type View
            case 2:
                {
                    oQC_Rework.nViewToDisplay = 3;
                    return View("GetQCDetails2", oQC_Rework);
                }
        }
    }
    // Should not get here at this stage!
    return View("NotFound", oQC_Rework);
}

The model’sproperty nViewToDisplay controls which Views get displayed.

When I debug the code, before the View GetSecondaryReferenceNumber2 gets called, the value in oQC_Rework.nViewToDisplay is set to 2 … but in the view itself it is "1′!!

What am I doing wrong?

Many thanks …

you don’t show the view code, but most likely its something like:

   @Html.HiddenFor(m=>m.nViewToDisplay)

with the html helpers, the lambda expression is just to get the name. ("nViewToDisplay") in your case. this name is then used to lookup the value. The postback form collection is searched before the ViewBag.Model (where you changed the data). so the postback
value is used.

just use a vanilla hidden field:

  <input type="hidden" name="nViewToDisplay" value="@Model.ViewBag.nViewToDisplay" />

or original helper that takes the value

   @Html.Hidden("nViewToDisplay",ViewBag.nViewToDisplay)

The type or namespace name 'WebGrid' could not be found (are you missing a using directive or an assembly reference?)

i am getting this kind of error message while running the programm as compilation error. previously i didn’t get this kind of error message but suddenly i am getting the error. 

previously in all modules it’s working fine but suddenly in all the modules i am getting the same error. 

what’s problem behind on this

Hi,

did you uninstall / update a nuget package related to System.Web.Helpers?

Grz, Kris.

no i didn’t uninstall any package but in references i have this System.Web.Helpers

Hi,

do you have a CVS ready so that you can go back in history of your code to a state where it worked? If so check the differences. Likely some using statement got lost.

Grz, Kris.

Hi,

You may not have "WebGrid.*.dll" with your project, or you may update your project, and "WebGrid.*.dll" is incompatible. Or accidentally deleted from your project dll libs.

You may need to add reference again to your project.

Please check carefully and Have fun

i was installed the webgridmvc from nuget also but it is not working

Hi,

Make sure that name is "WebGrid" or "WebGridMVC". It is case sensitive. Please check.

I’ll try to test it and come to you then.

WebGrid grid = new WebGrid();

i am using this thing only from the entire project upto few days back also it’s working fine. right now we are trying to add a new view with the webgrid then we are getting this

problem and we run the entire project which have this webgrid all are getting the same error. we shocked what happend and how to regetting the Webgrid we dont want to change any other things right now because i have so many forms this webgrid

Hi,

If you install webgridmvc, you must use "@using WebGridMvc;" for the nameSpace.

Please post the detail errors.

if i changed to WebgridMvc then i have to change my entire code where i have this webgrid this will again long time taken thing 

 Layout = "~/Views/Shared/_AdminLayout.cshtml";
Line 5:  
Line 6:      WebGrid grid = new WebGrid();
Line 7:      grid.Bind(Model,
Line 8:                autoSortAndPage: true

CS0246: The type or namespace name ‘WebGrid’ could not be found (are you missing a using directive or an assembly reference?)

this error i am getting when i run the page 

Are you using the appropriate @using statement?  If so, is it at the top of the page or the web.config file?  If it is in the web.config then try closing VisualStudio then re-opening it as that config setting isn’t dynamically processed as you change it. 
Also check the appropriate dll is in the bin folder.  Something else you can test to see if it is a missing assembly or missing "using" is to use the full classname, eg the namespace and classname, and see if the class is found then.

the problem is solved after remove the System.Web.Helpers from the references and add it again. But i got another problem while do it when  i tried to run the program i am getting the following error

An exception of type ‘System.TypeLoadException’ occurred in Microsoft.Owin.Security.Cookies.dll but was not handled in user code

Additional information: Could not load type ‘Microsoft.Owin.Security.AuthenticationDescription’ from assembly ‘Microsoft.Owin, Version=2.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35′.

Hi Siva_540,

Thanks for your post.

Siva_540

Additional information: Could not load type ‘Microsoft.Owin.Security.AuthenticationDescription’ from assembly ‘Microsoft.Owin, Version=2.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35′.

You can try install the package from Manage NuGet packages

Microsoft.Owin.Security

Hope this can be helpful.

Best Regards,

Eileen

i have already this in my project

[RESOLVED]Not able to get name of the image button on Controller side

Hello There, 

I am new to MVC and facing lot of issues :(

I have one image, acting as a button, when I clicked on it, it post back, but not able to find its name in Action. Here is my code snippet

View :-

@using (Html.BeginForm())
{

<input type="image" value="AddRoutine" name="button" src="~/Images/Add.png" id="imgAdd" title="Add" alt="Add" />

}

Controller :- 

[HttpPost]
public ActionResult Index(string button)
{
          // the parameter "button" is always comes null 

it is working fine when I use input type button instead of image 

Where I am doing mistake, what is the problem with input type image ?

Please help me out 

Thanks
Ash

An input type="image" is not an input that can carry a value to the server

try this

<button type="submit" value="AddRoutine" name="button" >
	
    <img src="~/Images/Add.png"  title="Add" alt="Add"/>
	
</button>

thats because the image posts two values containing the x & y positions. name.x and name.y. so you need an object:

public class ImageValue
{
   public int x {get; set;}
   public int y {get; set;}
}

[HttpPost]
public ActionResult Index(ImageValue button)
{

} 

[RESOLVED]Layout Needs a Model

Hi All,

I am working on a project for which the UI was created by someone else.  The project has a Partial View called _ApplicationLayout.cshtml that renders on every view page in the project.   It also hosts several partial views, one of which is the "_Comments.cshtml"
view in which I need to display all of the comments from the database that are associated with the application in the right bar of the layout.  I cannot use a View Model in the _Comments.cshtml partial, because it is rendered in the _ApplicationLayout.cshtml
and of course the View Model clashes with all of the other View Models throughout the project.  Can anyone tell me just how can solve this problem?  The comments do need to show on every page (view) in the project.

You can do it via two different ways,

  1. Call @Html.RenderAction  rather than partial to render the result of an action method, that will give you chance to separate out the code with strongly typed model
  2. Create a base controller and initialize the data and assign it to ViewBag which is required for comments view, now all controllers will inherit from base controller and they will have the data available.

I would prefer the first approach as it is a MVC way of doing things and avoid any accidental miss of controller inheritance.

Either move the comments-partial to the actual View, or replace the Partial helper with an Action helper and pass it an ID/value to process data and return a partial view

Example–

Instead of:

@Html.Partial("_Comments")

do:

@Html.Action("GetComments", new { id = X })

where X could be a ViewBag.Value or a URL parameter, example:

@Html.Action("GetComments", new { id = ViewBag.BlogID })

public ActionResult GetComments(int id)
{
  var comments = db.Comments.Where(c => c.BlogID == id).ToList();

  return PartialView("_Comments", comments);
}

The problem is that there  will be a list of comments, and there is a "textarea" for adding more comments on the fly.  Will the solution you suggested still work?  I don’t have the option of moving the Partial out of the _ApplicationLayout.cshtml.  Also,
how can I specify the controller where the ActionResult is in the code:

@Html.Action("GetComments"new { id = ViewBag.loanApplicationId})
?

You can specify the Controller as another parameter of the Action helper:

@Html.Action("GetComments", "Home", new { id = ViewBag.loanApplicationId })

As for your text-area, just give this input a name that matches the post-action param:

@using Html.BeginForm("AddNewComment"))
{
@Html.Hidden("ApplicationId", ViewBag.loanApplicationId)
<div>
Add Comment: @Html.TextArea("NewComment")
</div>

<input type="submit" value="Submit" />
}

Action:

[HttpPost]
public ActionResult AddNewComment(int ApplicationId, string NewComment)
{
  // use ApplicationId to fetch the record
// add NewComment to the record

return redirectToAction("Index"); }

That’s a fairly simple solution.  If you have questions, ask away

Okay, I think I understand it now.  The only other question I have is if they should add a comment (remember they could be on any View page in the project), Once the comments pane is updated the user is has to return to the same view.  From what I have read
online, this should be some sort of "child action only".  Is that correct?

By the way, you are really awesome to have taken the time to help me!  I wish I could send you a gift!

So what you want to do is use an Ajax form, process the comment, then return a fresh instance of your Partial view back to the main View.  Let’s go through the whole thing, but with the ajax:

1) In your _Layout, you’ve got the Html.Action(…) helper.  We should wrap this in a <div> tag because we’re going to update this after our ajax-post

<div id="commentsDiv">
  @Html.Action("GetComments", "Home", new { id = ViewBag.loanApplicationId })
</div>

2) In your partial view, you’ve got your form that allows the user to add a comment.  We’re going to change this to an Ajax form

@using (Ajax.BeginForm("AddNewComment", new AjaxOptions { HttpMethod = "POST", UpdateTargetId = "commentsDiv" }))
{
  @Html.Hidden("AppId", ViewBag.loanApplicationId)
  <div>
    Add Comment: @Html.TextArea("NewComment")
  </div>

  <input type="submit" value="Submit" />
}

3) In the post-action, we process the new comment, then return our *UPDATED* _Comments partial view back to the view

[HttpPost]
public ActionResult AddNewComment(int AppId, string NewComment)
{
  // use ApplicationId to fetch the record
// add NewComment to the record

var comments = db.Comments.Where(c => c.ApplicationId == AppId).ToList();

return PartialView("_Comments", comments); }

And that’s it!  Now it’s important to note that you MUST have the unobtrusive-ajax scripts included in your View.  If you are unsure whether you have these, check your Scripts folder (download them from the NuGet manager if needed).

I received the following error when I tried to run this:

"Additional information: Error executing child request for handler ‘System.Web.Mvc.HttpHandlerUtil"

I tried to run in without the Id in the parameters and just hardcoded the ID in the method just for testing.  Here is what is in my _ApplicationLayout:

  <div id="PageClassDiv" class="@(ViewBag.PageClass) APPLICATION"><!-- page content container-->
        
        @Html.Partial("~/Views/Shared/_NavigationView.cshtml") <!-- Navigation Partial View -->
        @Html.Partial("~/Views/Shared/_SearchAccordionView.cshtml") <!-- Search Accordion Partial View -->

        <!-- All applications should have comments and sidebar ============================================================================================-->
        @Html.Partial("~/Views/Shared/_SideBarView.cshtml");
        @*@Html.Partial("~/Views/Shared/_CommentsView.cshtml");*@
        @Html.Action("GetComments", "LoanApplication")
        
        <!-- content ============================================================================================-->
        @if (angularEnabled)
        {
            <div class="container" ng-app="@angularAppName">@RenderBody()</div>
        }
        else
        {
            <div class="container">@RenderBody()</div>
        }
    </div><!-- end page content container-->

This is the CommentsView:

<span class="comments">
    <a id="right-menu" href="#right-menu" class="icon-comments"></a>
</span>
<span class="clear"></span>

<div id="sidr-right" class="sidr right">
    <header>
        <h4> Application Notes </h4>
        <a href="#" class="icon-print"></a>
        @using (@Html.BeginForm("Comment", "LoanApplication"))
        {
           @Html.TextArea("Comment")
        @*<textarea cols="100" rows="2" name="Comment" placeholder="Leave Comment ..."></textarea>*@
            <input value="Add Comment" type="submit" />
        }
    </header>

And this is what is in my controller:

  [HttpGet]
        [Route("GetComments")]
        public async Task<ActionResult> GetComments()
        {
            var loanApplicationServiceProxy = base.ServiceProvider.LoanApplicationServiceProxy;

            var comments = await loanApplicationServiceProxy.GetLoanApplicationCommentsByLoanApplicationIdAsync(loanApplicationId) ?? new List<LoanApplicationComment>();
            
            return PartialView("_CommentsView", comments);
        }


 [HttpPost]
        [Route("Comment")]
        public async Task<ActionResult> Comment(FormCollection form)
        {

            var loanApplicationServiceProxy = base.ServiceProvider.LoanApplicationServiceProxy;
            var userId = this.User.Identity.GetUserId();
            string comment = Request.Form["Comment"];
            var applicationComment = new LoanApplicationComment
            {
                Comment = comment,
                CreatedDate = DateTime.Now,
                LoanApplicationId = loanApplicationId,
                Id = Guid.NewGuid(),
                CreatedBy = Guid.Parse(userId)
            };
            await loanApplicationServiceProxy.PutLoanApplicationCommentAsync(applicationComment);

            var comments = loanApplicationServiceProxy.GetLoanApplicationCommentsByLoanApplicationIdAsync(loanApplicationId);

            return View(comments);
         
        }

The code in the Controller "GetComments" never gets hit.  The application throws an error as soon as I try to navigate to a View page that has the comments pane.

BeeDev

The code in the Controller "GetComments" never gets hit.

take off the [HttpGet] and [Route("GetComments")] annotations, and see if that works.

I was able to get it to hit the controller, but I can’t figure out how to actually display the comments.  I’m used to using @model.Comment, or something of the sort, but there is not model, so how do I specify the fields that I need to display?  I must display
the user name, date and time of comment, along with the comment.

This is going beyond the original scope of the question.  If I understand everything correctly, your _Comments partial view displays rows of comments that include user name, date & time of comment, and the comment.

The model for Comment may look something like this (I’m just guessing since you have not posted the actual model):

public class Comment
{
public int CommentId { get; set; } public string Comment { get; set; }
public string UserName { get; set; } public string CDate { get; set; }
public int App_ID { get; set; } }

The model includes a primary index key (CommentId), the other required fields, and also a foreign key reference (App_ID)

The _Comment partial view may then look like this:

@model IEnumerable<AppName.Models.Comment>

<h2>Submit Comment</h2>

@using (Ajax.BeginForm("AddNewComment", "LoanApplication", new AjaxOptions { HttpMethod = "POST", UpdateTargetId = "commentsDiv" }))
{
  @Html.Hidden("AppID", ViewBag.loanApplicationId)
  <div>
    Comment: @Html.TextArea("NewComment")
  </div>

  <input type="submit" value="Submit" />
}

<h2>Comments</h2>

@foreach (var item in Model)
{
  <div>
    <dl class="dl-horizontal">
      <dt>Username</dt>
      <dd>@Html.DisplayFor(modelItem => item.UserName)</dd>

      <dt>Date</dt>
      <dd>@Html.DisplayFor(modelItem => item.CDate)</dd>

      <dt>Comment</dt>
      <dd>@Html.DisplayFor(modelItem => item.Comment)</dd>
    </dl>
  </div>
}

To explain, our @model is a LIST of comments that will be passed to the partial view.  At the top I’ve included the AJAX form, which allows a user to submit their comment.  Below the form is the Comments section, which loops through each comment, displaying
the User, the Date, and the Comment (I used DL formatting but you can use TABLE or DIV, etc).  Now when the form posts and finishes processing, we’ll be returning a fresh _Comments partial view, which will replace the old one.  We use "UpdateTargetId" to specify
where to update.

Your AJAX post-action in your "LoanApplication" controller:

[HttpPost]
public ActionResult AddNewComment(int AppID, string NewComment)
{
  // create new comment object
  var comment = new Comment();
  comment.Comment = NewComment;
  comment.UserName = User.Identity.Name;
  comment.CDate = DateTime.Now;
  comment.App_ID = AppID;

  // add comment to db
  db.Comments.Add(comment);
  db.SaveChanges();

// query new comments list and return to partial view var comments = db.Comments.Where(c => c.App_ID == AppID).ToList(); return PartialView("_Comments", comments); }

I’ve commented this for explanation.

Your _Layout view now only needs to have the initial Action helper inside a named DIV

<div id="commentsDiv">
  @Html.Action("GetComments", "LoanApplication", new { id = ViewBag.loanApplicationId })
</div>

As said earlier, once the AJAX form posts, a new version of _Comments partial view will replace the contents of "commentsDiv".

Lastly, the "GetComments" action (in the LoanApplication controller):

public ActionResult GetComments(int id)
{
  var comments = db.Comments.Where(App_ID == id).ToList();

  return PartialView("_Comments", comments);
}

And that’s it.  There’s the entire solution…  If all of this works for you, please take a moment to mark all my responses as answers, as they all answer each of your subsequent questions.  Thanks.

Okay, I figured out that I can put a model in the _CommentsView.cshtml since it is being rendered with an @Html.Action.  Thanks for ALL of your help!  You are awesome!!!

[RESOLVED]Html.Helpers or Html tags ?

When we are developing our views, we can set codes as HTML.Helpers or write them as HTML tags.
However what’s best ?

EXAMPLE: CREATING A HYPERLINK

1. @Html.ActionLink("About this Website", "About")

2. <a href="/Home/About">About this Website</a>

a) So what should I use ? Should I write the HTML tags directly without razor or use helpers ?
b) If I use helperss would it cause an extra processing once I have to convert Razor to HTML ?

You can choose either. I personally use both, depending to where I’m linking.

For members and registered users, on an ASP.net project, I usually use the helpers, and on any pages accessible to unauthenticated users I use the <a href=""></a> tags.

If you use the Html.ActionLink helper, the url will always be constructed properly regardless of changes in the hosting environment, or changes between development, testing and production environments. This might not be an issue to you in which case feel
free to hard code your links. 

I have full control over my hosting environment and make sure that the development environment mirrors it as much as possible. Despite that, I use the helpers just in case. 

aganeto

If I use helperss would it cause an extra processing once I have to convert Razor to HTML ?

Yes, but it is so insignificant that if you have to worry about it, you have much bigger problems.

Webgrid Questions

I am wanting to create a webpage that has a webgrid where you can select a row and it will show the details of that row below the webgrid for editing. Could someone provide an example of how to do this?

I wrote and article about doing this using the Web Pages framework. You can adapt it to MVC: http://www.mikesdotnetting.com/Article/168/The-WebGrid-Helper-Making-Selections

Thank you for the reply. I found that article very helpful. Except when you got to this part:

@if(grid.HasSelection){
    var book = grid.SelectedRow;
    @RenderPage("~/Partials/EditBook.cshtml", new { Book = book } )
}

How did you get the value for book? I do not see anywhere in the code you gave where that is located. 

The second parameter of the RenderPage method takes an anonymous object representing data to be passed to the partial. In this case, the value (book, with a lower case b) is the SelectedRow property of the grid. The SelectedRow property is a dynamic
object whose properties are made up from the column names. So book is a dynamic object with BookId, Title, Description etc properties.  This is passed to the Partial’s
PageData property (also accessible via the dynamic Page property). So in the partial, the Id of the book is obtained like this:

var bookid = Page.Book.BookId;

Thank you for the response. Sorry for my delayed response. But I am trying to do this in a MVC format, so I would not want to access the data from a webpage. How do you pass that value to a controller to then access the data?

You still need to pass the data to the View. In MVC, you get the data within the controller and pass it to the view either as a strongly typed model or in ViewBag. Then you will bind the model to the WebGrid in the View. 

I am trying your method and actually querying the database from the partial view but I am using Entity Framework to access the database and I do not have the functionality do the Database.Open command. Again is there a way to pass the selected value from
the webgrid to my controller and then render that partial page by a strongly typed Edit page?

Partial View won't Render List from Database

I have been battling this all day.  Thanks to JohnLocke that I have gotten this far.  I am rendering a Partial View with the Following:

        @Html.Action("GetComments", "LoanApplication")

The partial looks like this:

  @model Portal.ViewModel.Comments.LoanApplicationCommentsViewModel


  @foreach(var item in Model.Comments)
            {
                @item.Comment
            }

The Controller Action looks like this:

[HttpGet]
        [Route("GetComments")]
        public async Task<ActionResult> GetComments()
        {
            var loanApplicationServiceProxy = base.ServiceProvider.LoanApplicationServiceProxy;

            var comments = await loanApplicationServiceProxy.GetLoanApplicationCommentsByLoanApplicationIdAsync(loanApplicationId) ?? new List<LoanApplicationComment>();
            
            var commentsList = new LoanApplicationCommentsViewModel()
            {
                Comments = comments                }
            };
    return PartialView("_CommentsView", commentsList);

Here’s the problem…although the "list" is not empty when the Partial View tries to render it throws an error.  However, if I use the EXACT same code in a Main view, the list is displayed.  The other twist is that if I change the above code to "hardcode"
a comment (like the example below), the Partial displays fine.  What am I missing here?  I’m pulling my hair out.  ANY and ALL assistance is appreciated!

The code below works for the partial (the only difference is that the list is hardcoded).

            var commentsList = new LoanApplicationCommentsViewModel()
            {
                Comments = new List<LoanApplicationComment>{
                    new LoanApplicationComment{
                        Id = Guid.NewGuid(),
                        Comment = "This is a Test Comment",
                        CreatedBy = Guid.NewGuid(),
                        CreatedDate = DateTime.Now,
                        LoanApplicationId = loanApplicationId
                    }
                }
            };
    
            return PartialView("_CommentsView", commentsList);

what is the variable "loanApplicationId" in this line?

var comments = await loanApplicationServiceProxy.GetLoanApplicationCommentsByLoanApplicationIdAsync(loanApplicationId) ?? new List<LoanApplicationComment>();

Its a Guid.  I have it hardcoded in at the top with private readonly Guid loanApplicationId = new Guid("blah-blah-blah").  It’s a real Guid pointing to a real record.  I did figure out that it does NOT like the await, but everything in the project (which
I didn’t create) is all asynchronous calls.  Even if a hardcode the "new" comment, if I don’t comment out the above line, the @Html.Action on the Partial throws an error.

Getting data of json array

I create an array with javascript that has some ids. I pass them back to my controller like so

$.ajax(
{
url: "/Home/GetChildKeys",
data: { ids: nodeKeys },
dataType: "json",
type: "GET"
}).done(function (result) { });

What I’m not sure on is how I get that data in my c# code to work with it. Here’s my function in my controller

//how do I get the array passed in as an argument
        [HttpGet]
        public JsonResult GetChildKeys(object var)
        {
            //need to figure out how to read id data and then pass back child keys
            return Json("foobar", JsonRequestBehavior.AllowGet);
        }

The param you choose for your ‘data’ option in the ajax-request must match the param of your post-action. 

[HttpGet]
public JsonResult GetChildKeys(someType ids)
{
...

Is nodeKeys a list of objects, or a string?  That will determine the "someType" above

I knew I’d have to get the type, I just wasn’t for sure what type it would be.

nodeKeys is just a javascript string array;

Something like 

var nodeKeys = ["cat_1", "cat_2", "cat_3"];

That’s not json, but anyway, try

string[] ids

or

List<string> ids

Then you could do

[HttpGet]
public JsonResult GetChildKeys(string[] ids)
{
foreach (var id in ids)
{
// process each id here
}

...
}

I was under the impression if I sent the data like this (underlined in bold)

$.ajax(
{
url: "/Home/GetChildKeys",
data: { ids: nodeKeys },
dataType: "json",
type: "GET"
}).done(function (result) { });

that it would convert that to json for me?

The "data" node will be json, but the data you are passing in the "ids" property is just a plain javascript array.

hi,

usually ajax communication more serialized content, while receiving  action method have to serialise as per mention data type, 

client : var array1 = ["A", "B", "C", "D"];
server : public JsonResult AjaxCallTest(List<string> postedModel){ //code…… }

client : var array = [1, 2, 3, 4, 5];
server : public JsonResult AjaxCallTest(List<string> postedModel){ //code….. }

or just pass json string, then in controller action have to parse posted json to respective model object.

Ref : serializing and deserializing json in c#

Thanks,

Jai

So how do I go about passing that array back to my application?

Basically, there’s some code that runs through a treeview and pulls the ids of any checked items and pushes them into the array. So, I need to send that array of ids back to my controller as json data. I don’t really care how they get there, array, list,
etc. but I just need to be able to loop through them. Ideas?

hi,

Client :

var selectedItems = [1, 2, 3, 4, 5]; // try to push your selected item.

$.ajax({
url: "/Account/AjaxCallTest/", //your url
traditional: true,
dataType: "json",
type:’post’,
data: { ids : selectedItems },
success:function(data) { 
},
error: function (errorMsg) {
}
});

Server:

[HttpPost]
public JsonResult AjaxCallTest(List<int> ids )
{
// your logic…
}

Thanks,

Jai.

That’s what I tried after your first post with no luck. This is what I have

var nodeKeys = ["cat_1", "cat_2", "cat_3"];

$.ajax(
{
url: "/Home/GetChildKeys",
data: { ids: nodeKeys },
dataType: "json",
type: "GET"
}).done(function (result) { });

C# 

        //how do I get the array passed in as an argument
        [HttpGet]
        public JsonResult GetChildKeys(List<string> ids)
        {
            //ids is still null
            var foo = ids;

            //need to figure out how to read id data and then pass back child keys
            return Json("foobar", JsonRequestBehavior.AllowGet);
        }

http://forums.asp.net/t/1934215.aspx?Using+jQuery+ajax+to+call+asmx+webservice+methods

either add

contentType:
"application/x-www-form-urlencoded; charset=UTF-8",

to your $.ajax call, or try

data: JSON.stringify({ ids: nodeKeys }),

I’ve tried both of those and ids is still null

nodeKeys = ["cat_1", "cat_2", "cat_3"];
$.ajax(
{
url: "/Home/GetChildKeys",
data: JSON.stringify({ ids: nodeKeys }),
dataType: "json",
type: "GET"
}).done(function (result) { });

and even

nodeString = "cat_1,cat_2,cat_3";
$.ajax(
{
url: "/Home/GetChildKeys",
data: "{keys: ‘" + nodeString + "’}",
dataType: "json",
type: "GET"
}).done(function (result) { });

You have to set the correct contentType too so the service knows how to interpret the data you are sending.  As well as the link I posted with all the examples, look at this to see how you can use the browser’s dev tools to see what is being sent and what
the response is.

http://forums.asp.net/t/1982579.aspx?Using+the+browser+s+dev+tools+to+diagnose+ajax+problems+and+other+things+

[RESOLVED]Issue with Razor and VB.net Supplying a default value

I have been able to do this with C# but with VB.net in the view I am having issues with syntax.

C# works great:
@Html.TextBoxFor(model => model.Address, new { @class="BTCaddress", @Value="" + ViewBag.Address + "" })

Not sure how to format in VB.net? I also have issues getting it to work with EditorFor:

Regular scaffolded code:
@Html.EditorFor(Function(model) model.Company, New With {.htmlAttributes = New With {.class = "form-control"}})

What I have tried:
@Html.EditorFor(Function(model) model.Company, New With {.htmlAttributes = New With {.class = "form-control", @Value="" & @ViewBag.Company & "" }})

Should I be using TextboxFor  in VB.net for this and how would I format it?

Hi,

Based on my test in the MVC 5 project, I found that we can’t set the default value by specify the data to the value.

For the Html.XXFor method, the default value should be based on the field value of Model. So, you need to create an instance with the default value and return to the view. You also could use
Html.TextBox method.

belcherman

@Html.TextBoxFor(model => model.Address, new { @class="BTCaddress", @Value="" + ViewBag.Address + "" })

Not sure how to format in VB.net? I also have issues getting it to work with EditorFor:

The VB code should be:

@Html.TextBoxFor(Function(m) m.Address, New With {.class = "BTCaddress",.value=ViewBag.Address})

Best Regards

Starain Chen