Category Archives: PlaceHolder

PlaceHolder

[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]Strange behavior from Create View

I have an ASP.Net MVC 4 web app.  I  have this one particular controller.  The index view for this controller has three partial views on it.  The first partial view always loads when the view is called.  It uses a renderAction html helper.  The other two
are called as a result of ajax function calls within the create view.

The index view has a JQuery datatables library included which is built using JqueryUI.  There are no JQueryUI components on the Create View.

As the result of a button click, the Create view calls a function which first calls one ajax function to save the data to the database, then another ajax call to the action used by the renderAction to build the first partial view.  This function was devised
months ago and has been running without an issue.   Then suddenly today, the button click would save the data, then open the index view.  This was not the expected behavior.  When I stepped through the code line by line I found that the pratial view was in
fact bveing loaded into the proper location on the create view.  And in fact when doing so the proper window opened in IE.  But then a bunch of additional code in modernizer, Jquery-1.8.2 and jQuery-UI-1.8.24 started running and when it completed it opened
on the Index view.  I have no idea how this happened.  See the code below

First I called an ajax like so

    $(function () {
        var PopulatePRs = function () {
            ////debugger
            var sURL = '@Url.Action("CreatePurchaseRequest", "AJAXFunctions")';
            var goURLid = 0;
            var form = $("#PRCreate");
            var bError = false;
            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 () {
                            goURLid = data;
                        });
                    }
                    else {
                        debugger
                        returnedInfo = 'An Error has occurred. Your new PR was not saved to the database.';
                        bError = true;
                        goURLid = 0;
                    }
                },
                error: function () {
                    debugger
                    returnedInfo = 'An Error has occurred. Your new PR was not saved to the database.';
                    bError = true;
                    goURLid = 0;
                }
            });

This works fine.   I have verified in the database that the ajax call was successful.  Then the following ajax function is called to call the action that rebuilds the partial view.

           debugger
            //if (!bError) {
            var sURLRepost = '@Url.Action("PurchaseRequestTable", "PR")' + '/' + goURLid;
            var options = {
                url: sURLRepost,
                type: "get",
                async: false
            };
            //alert(options.url);
            $.ajax(options).done(function (data) {
                debugger
                $("#PRtableView").replaceWith(data);
            });

            if (!bError) {
                sResultMessage = "The new Purchase Request has been saved to the database.nClick below to add CLINs and CDRLs.";
                $("#PRCreated").text(sResultMessage).toggle();
            }
            else {
                sResultMessage = returnedInfo;
                $("#PRCreated").text(sResultMessage).toggle();
            }

The action is properly called the ajax call which I was able to verify by putting a breakpoint in the action and stepping through it and I was able to hover over the "data" variable and verify that the proper html was being returned to replace $("#PRtableView"). 
Finally I was able to verify the sResultMessage was replacing the text of $("#PRCreated").  Then I actually saw the window open looking as it is supposed to.

Then the part of modernizer that starts with the below code ran:

window.Modernizr = (function( window, document, undefined ) {


    var version = '2.6.2',


    Modernizr = {},

    /*>>cssclasses*/

    // option for enabling the HTML classes to be added

    enableClasses = true,

    /*>>cssclasses*/

Then in JQuery-1.8.2 the function that starts with this:

(function( window, undefined ) {
var
	// A central reference to the root jQuery(document)
	rootjQuery,

	// The deferred used on DOM ready
	readyList,

	// Use the correct document accordingly with window argument (sandbox)
	document = window.document,
	location = window.location,
	navigator = window.navigator,

	// Map over jQuery in case of overwrite
	_jQuery = window.jQuery,

Then this function

(function( $, undefined ) {


// prevent duplicate loading

// this is only a problem because we proxy existing functions

// and we don't want to double proxy them

$.ui = $.ui || {};

if ( $.ui.version ) {

	return;

}

Then this function

function( $, undefined ) {



// jQuery 1.4+

if ( $.cleanData ) {

	var _cleanData = $.cleanData;

	$.cleanData = function( elems ) {

		for ( var i = 0, elem; (elem = elems[i]) != null; i++ ) {

			try {

				$( elem ).triggerHandler( "remove" );

			// http://bugs.jquery.com/ticket/8235

			} catch( e ) {}

		}

		_cleanData( elems );

	};

} else {

	var _remove = $.fn.remove;

	$.fn.remove = function( selector, keepData ) {

		return this.each(function() {

			if ( !keepData ) {

				if ( !selector || $.filter( selector, [ this ] ).length ) {

					$( "*", this ).add( [ this ] ).each(function() {

						try {

							$( this ).triggerHandler( "remove" );

						// http://bugs.jquery.com/ticket/8235

						} catch( e ) {}

					});

				}

			}

			return _remove.call( $(this), selector, keepData );

		});

	};

}

Then in JQuery-ui-1.8.24

(function( $, undefined ) {


var mouseHandled = false;

$( document ).mouseup( function( e ) {

	mouseHandled = false;

});

then

function( $, undefined ) {


$.widget("ui.draggable", $.ui.mouse, {

	widgetEventPrefix: "drag",
...

then

(function( $, undefined ) {


$.widget("ui.droppable", {

	widgetEventPrefix: "drop",

	options: {

		accept: '*',
....

and a few more $.widget methods.

And when all of these finished, then the index view was opened.

Like I said it did not do that from a couple of months ago up to a couple of days ago.  It did not do this when I first ran it this morning.  It just started to do this, this morning at a demonstration for the customer, and has been doing this ever since.

I am baffeled.  If anyone can point me in the right direction I would be most grateful.

Found it.  This page
http://forums.asp.net/p/2010964/5786750.aspx?p=True&t=635478678680887055&pagenum=1
 I was advised to put href = "" in my links to make the syle of a link appear on the page.  I had forgotten that I read somewhere that when no index is passed to the url,
then the user is routed to the index method of the controller.  That is what happened here after I made the change referenced above. 

So I will have to hard code a style just for these elements in the style sheet.

Hi joeller,

If the href attribute is not present, the <a> tag is not a hyperlink. In HTML5, if the <a> tag has no href attribute, it is a placeholder for a hyperlink.

# HTML <a> href Attribute

http://www.w3schools.com/tags/att_a_href.asp

Best Regards

Starain Chen

[RESOLVED]Render Dynamic Forms model in Razor View

Hi,

 

Im using Dynamic Forms in ASP.NET MVC sample project from this link https://mvcdynamicforms.codeplex.com/  to be used in my MVC 5 project.

 

Waht i need is to call the dynamically generated Form model to be rendered in razor view as it is currently rendered in asp.net mvc ViewPage.

here’s the current Model,Controller and how the view has called the Form object. How can i call the form object in mvc 5 razor view.

 

FormProvider Model

=================================

    public static class FormProvider

    {

        public static Form GetForm()

        {

        }

    }

 

 

HomeController

===========================

    public ActionResult Demo1()

        {

          

             var form = FormProvider.GetForm();

             

              form.Serialize = true;

             return View("Demo", form);

     }

 

 

 

ASP.NET MVC View

==================

 

     <%@ Page Language="C#" MasterPageFile="~/Views/Shared/Site.Master" Inherits="System.Web.Mvc.ViewPage<MvcDynamicForms.Form>" %>

 

     <asp:Content ID="indexContent" ContentPlaceHolderID="MainContent" runat="server">

 

 

      <%Html.BeginForm(null, null, FormMethod.Post, new { enctype = "multipart/form-data" }); %>

   

 

      <%=Model.RenderHtml(true) %>

   

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

           <%Html.EndForm(); %>

 

        </asp:Content>

@model MvcDynamicForms.Form
@{
    // set layout if required etc
}
@using(Html.BeginForm(null, null, FormMethod.Post, new { enctype = "multipart/form-data" })){ 
    @Model.RenderHtml(true)  
    <input type="submit" value="Submit" />
}

Thanks Mike. it worked…!

@Model.RenderHtml(true)  didn't render the html, instead it displays the string as is, but when it is wrapped in HTML.Raw(Model.RenderHtml) 
it did work.


[RESOLVED]multiple search option with cascading dropdown and MVC.Paging

how can i use multiple search options to get number of paged records

multiple search option like country ,state ,city ,gender, and etc…

here i created a controller browseallmemmbers where search criteria is working 

private const int defaultPageSize = 10;
       
        private IList<Profile> getAllmembers = new List<Profile>();
        public ActionResult BrouseAllMem(int? page, long? stateid, long? countryid,long? cityid)
        {

            int currentPageIndex = page.HasValue ? page.Value : 1;

            ViewData["countryid"] = countryid;
            ViewData["Stateid"] = stateid ;
            ViewData["cityid"] = cityid ;
           
            IList<Profile> members = this.getAllmembers;

           
            IQueryable<Profile> mm = db.Profiles.OrderByDescending(c => c.pid);
            if (countryid > 0)
            {
                
                mm = mm.Where(p => p.countryid == countryid);
            }
            if (stateid > 0)
            {
                mm = mm.Where(p => p.stateid == stateid);
            }
            if (cityid > 0)
            {
                mm = mm.Where(p => p.cityid  == cityid);
            }

           
            members = mm.OrderByDescending(p => p.pid).ToPagedList(currentPageIndex, defaultPageSize);
 
            ViewBag.cityid = new SelectList(db.citytables, "cityid", "cityname", ViewData["cityid"]);
            ViewBag.countryid = new SelectList(db.Countries, "COUNTRYID", "countryname", ViewData["countryid"]);
            ViewBag.stateid = new SelectList(db.states, "stateid", "statename", ViewData["stateid"]);
                      
            return View(members);
        }

View where result is displaying

@*@model IEnumerable<LovNMarProj.Models.Profile>*@
@using MvcPaging
@model IPagedList<LovNMarProj.Models.Profile>
@{
    ViewBag.Title = "BrouseAllMem";
    Layout = "~/Views/Shared/_LayoutTEM.cshtml";
}
@using (Html.BeginForm("BrouseAllMem", "Home", FormMethod.Get))
{
<div class="page-header">
    <div class="panel panel-default">
        <div class="panel-heading">All Members</div>
        <div class="panel-body">
            <div class="col-sm-3 col-md-3 pull-left">
                <div class="input-group input-group-sm">
                    @*<input class="form-control" id="appendedInputButton" type="text" name="member_name" placeholder="Name" value="@ViewData["member_name"]" />*@
                   
                </div>
            </div>
            @Html.DropDownList("countryid", ViewBag.countryid as SelectList, "Select a Country", @ViewData["countryid"])

            @Html.DropDownList("stateid",null ,string.Empty , @ViewData["stateid"])

            @Html.DropDownList("cityid",null ,string.Empty , @ViewData["cityid"])

            <div class="col-sm-3 col-md-3 pull-right" >
                <button class="btn" type="submit">
                    <i class="glyphicon glyphicon-search"></i>
                </button>
            </div>
        </div>
        <ul class="list-group">
            
            @foreach (var item in Model)
            {
                var gender = "Female"; if (@item.gender == "M") { gender = "Male"; } 
                var pimage = "no_avatar.gif"; 
                if (@item.photo != null && @item.photo  != "") { pimage = @item.photo ; }
                
                
                
                <li class="list-group-item ">
                    <div class="row">
                        <div class="col-sm-9">
                            <p> <strong>@item.headline</strong></p>
                        </div>
                        <div class="col-lg-3 text-muted text-right small">
                            Joined On: @item.profiledate
                        </div>
                    </div>
                    <div class="row">
                        <div class="col-sm-1">

                            <img src="~/profilepic/@pimage" class="img-thumbnail" />
                        </div>
                        <div class="col-sm-3">
                            <h5>
                                @item.fname
                                &nbsp;
                                @item.lname<small>(@gender)</small>
                            </h5>
                            <p>
                                @item.Country.countryname  -
                                @item.state.statename -
                                @item.citytable.cityname 
                            </p>
                        </div>
                        <div class="col-sm-5">
                            About:<p> @item.whoami</p>
                        </div>
                        <div class="col-sm-3">
                           Looking For:<p> @item.lookingfor</p>
                        </div>
                    </div>








                </li>
            }

        </ul>
        <div class="panel-footer">
            <div class="pager">
                @Html.Raw(Html.Pager(
            new Options
            {
                PageSize = Model.PageSize,
                TotalItemCount = Model.TotalItemCount,
                CurrentPage = Model.PageNumber,
                ItemTexts = new ItemTexts() { Next = "Next", Previous = "Previous" },
                ItemIcon = new ItemIcon() { First = "icon-backward", Previous = "icon-chevron-left", Next = "icon-chevron-right", Last = "icon-forward" },
                TooltipTitles = new TooltipTitles() { Next = "Next page {0}", Previous = "Previous page {0}", Page = "Go to page {0}" },
                Size = Size.normal,
                Alignment = Alignment.centered,
                IsShowControls = true,
                IsShowFirstLast = true,
                IsShowPages = true
            }, new { countryid = ViewData["countryid"], stateid = ViewData["stateid"], cityid = ViewData["cityid"] }))
            </div>

        </div>
    </div>
</div>
}
<script type="text/jscript">
    $(function () {

        $('#countryid').ready(function () {


            //$('#stateid').empty();
            //$('#cityid').empty();

            $.getJSON('/Kas/StateList/' + $('#countryid').val(), function (data) {
                var items = "";
                $.each(data, function (i, stateid) {
                    items += "<option value='" + stateid.Value + "'>" + stateid.Text + "</option>";
                });

                $('#stateid').html(items);
                $('#stateid').trigger("change");

            });
        });



        $('#countryid').change(function () {

            $.getJSON('/Kas/StateList/' + $('#countryid').val(), function (data) {
                var items = '';
                $.each(data, function (i, stateid) {
                    items += "<option value='" + stateid.Value + "'>" + stateid.Text + "</option>";
                });
                $('#stateid').html(items);

            });
        });

        $('#stateid').change(function () {
            $.getJSON('/Kas/Citylist/' + $('#stateid').val(), function (data) {
                var items = '';
                $.each(data, function (i, cityid) {
                    items += "<option value='" + cityid.Value + "'>" + cityid.Text + "</option>";
                });
                $('#cityid').html(items);



            });
        });





    });

</script>

it shows the result properly but if i go to next page search criteria is gone

how to keep search result and paging both

 with one search option its works but with multiple search its not working

Hi pjpatil,

Base on your code, I found that you are using ViewData and ViewBag with same key, which are conflict, in other words, the
ViewData data will be override.

Please use the different key to store current search conditions.

To keep the conditions, you just need to store them as parameters in the URL (Html.PagedListPager), and in the action has the corresponding parameters to get that data.

Best Regards

Starain Chen

[RESOLVED]Set the condition for two Dropdownlists using viewbag

Hi am new to mvc………..am using two dropdowns ( one is for minimum salary and the other is max salary) getting data from the controller using viewbag…….but i need to set the condition min salary should be less than max salary  for two drop downs………..can
anyone help me to solve it……..

THIS IS MY VIEW

 <dt>Annual salary</dt>
                                                    <dd> <%= Html.DropDownListFor(model => model.AnnualSalary.MinimumLakhs, new SelectList(ViewBag.Annualsalarylakhs1),"Lakhs",new {style="display:inline; width:90px;",@id="txtMinimumLakhs",@class="mid-size mr10",@placeholder="Laks"})%>
                                                        <%= Html.DropDownListFor(model => model.AnnualSalary.MinimumThousands, new SelectList(ViewBag.AnnualSalaryThousands1),"Thousands",new {style="width:90px;",@id="txtMinimumThousands",@class="mid-size",@placeholder="Thousands"})%></dd>
                                                    <dt>&nbsp;</dt>
                                                    <dt>To</dt>
                                                    <dt>&nbsp;</dt>
                                                    <dd><%= Html.DropDownListFor(model => model.AnnualSalary.MaximumLakhs, new SelectList(ViewBag.Annualsalarylakhs1),"Lakhs",new {style="display:inline; width:90px;",@id="txtMaximumLakhs",@placeholder="Laks",@class="mid-size mr10"})%>
                                                        <%= Html.DropDownListFor(model => model.AnnualSalary.MaximumThousands, new SelectList(ViewBag.AnnualSalaryThousands1),"Thousands",new {style="display:inline; width:90px;",@id="txtMaximumThousands",@placeholder="Thousands",@class="mid-size"})%></dd>
                                                    </dl>

Thanks in advance………

I have 3 suggestions that you could try

1) on-select-change, check if the minimum value is less than the maximum value.  If false, disable the Submit button to prevent posting and display alert to correct the values.

2) on-form-submit, check if the minimum value is less than the maximum value.  If false, prevent submission and display alert to correct values.

3) Check values at the  controller level, and if false, return a ModelStateError message back to view (I would not let your post get to controller though)

I would personally use #2 as it only requires checking at submission time, and doesn’t send any data to the controller if your validation fails

$("form").submit(function( event ) {
  if ($("#MinimumLakhs").val() > $("#MaximumLakhs").val()) {
alert("Minimum Lakhs must be less than maximum Lakhs");
event.preventDefault();
}

// do the same for "Thousands" if necessary });

When you submit your form, this event handler gets triggered.  It will then check your minimum Lakh value against the maximum value.  If it is false (greater than the maximum), it will alert the user to correct it.  The "preventDefault" method cancels the
submit event, preventing the form from being passed to controller.

Thank  u JohnLocke

 

Thank u johnLocke but i need the condition as 

When i select the a value in the dropdown  minlakhs then the values in the  maxlakhs drop down should start the range from what i selected the minlakhs dropdown …….

For example when i select minlakhs dropdown value as 4lakhs the values in the max lakhs drop down should start the range from 4lakhs……

How can i do this using viewbag……..

Please help me anyone……..

Thanks in advance………..

[RESOLVED]Using viewbags How to set the condition for two drops….after selecting minsalary then maxsalary should start the same range from what i selected the minlakhs dropdown

Hi am new to mvc………..am using two dropdowns ( one is for minimum salary and the other is max salary) getting data from the controller using viewbag….this is my view

<dt>Annual salary</dt>
                                                    <dd> <%= Html.DropDownListFor(model => model.AnnualSalary.MinimumLakhs, new SelectList(ViewBag.Annualsalarylakhs1),"Lakhs",new {style="display:inline; width:90px;",@id="txtMinimumLakhs",@class="mid-size mr10",@placeholder="Laks"})%>
                                                        <%= Html.DropDownListFor(model => model.AnnualSalary.MinimumThousands, new SelectList(ViewBag.AnnualSalaryThousands1),"Thousands",new {style="width:90px;",@id="txtMinimumThousands",@class="mid-size",@placeholder="Thousands"})%></dd>
                                                    <dt>&nbsp;</dt>
                                                    <dt>To</dt>
                                                    <dt>&nbsp;</dt>
                                                    <dd><%= Html.DropDownListFor(model => model.AnnualSalary.MaximumLakhs, new SelectList(ViewBag.Annualsalarylakhs1),"Lakhs",new {style="display:inline; width:90px;",@id="txtMaximumLakhs",@placeholder="Laks",@class="mid-size mr10"})%>
                                                        <%= Html.DropDownListFor(model => model.AnnualSalary.MaximumThousands, new SelectList(ViewBag.AnnualSalaryThousands1),"Thousands",new {style="display:inline; width:90px;",@id="txtMaximumThousands",@placeholder="Thousands",@class="mid-size"})%></dd>
                                                    </dl>

 

When i select the a value in the dropdown  minlakhs then the values in the  maxlakhs drop down should start the range from what i selected the minlakhs dropdown …….

For example when i select minlakhs dropdown value as 4lakhs the values in the max lakhs drop down should start the range from 4lakhs……

These are the viewbags am getting from the controller

 public void GetAnnualsalarylakhs()
        {
            List<string> Annualsalarylakhs = new List<string>();
            Annualsalarylakhs.Add("<0.5");
            Annualsalarylakhs.Add("1");
            Annualsalarylakhs.Add("2");
            Annualsalarylakhs.Add("3");
            Annualsalarylakhs.Add("4");
            Annualsalarylakhs.Add("5");
            Annualsalarylakhs.Add("6");
            Annualsalarylakhs.Add("7");
            Annualsalarylakhs.Add("8");
            Annualsalarylakhs.Add("9");
            Annualsalarylakhs.Add("10");
            Annualsalarylakhs.Add("11");
            Annualsalarylakhs.Add("12");
            Annualsalarylakhs.Add("13");
            Annualsalarylakhs.Add("14");
            Annualsalarylakhs.Add("15");
            Annualsalarylakhs.Add("16");
            Annualsalarylakhs.Add("17");
            Annualsalarylakhs.Add("18");
            Annualsalarylakhs.Add("19");
            Annualsalarylakhs.Add("20");
            Annualsalarylakhs.Add("21");
            Annualsalarylakhs.Add("22");
            Annualsalarylakhs.Add("23");
            Annualsalarylakhs.Add("24");
            Annualsalarylakhs.Add("25");
            Annualsalarylakhs.Add("26");
            Annualsalarylakhs.Add("27");
            Annualsalarylakhs.Add("28");
            Annualsalarylakhs.Add("29");
            Annualsalarylakhs.Add("30");
            Annualsalarylakhs.Add("31");
            Annualsalarylakhs.Add("32");
            Annualsalarylakhs.Add("33");
            Annualsalarylakhs.Add("34");
            Annualsalarylakhs.Add("35");
            Annualsalarylakhs.Add("36");
            Annualsalarylakhs.Add("37");
            Annualsalarylakhs.Add("38");
            Annualsalarylakhs.Add("39");
            Annualsalarylakhs.Add("40");
            Annualsalarylakhs.Add("41");
            Annualsalarylakhs.Add("42");
            Annualsalarylakhs.Add("43");
            Annualsalarylakhs.Add("44");
            Annualsalarylakhs.Add("45");
            Annualsalarylakhs.Add("46");
            Annualsalarylakhs.Add("47");
            Annualsalarylakhs.Add("48");
            Annualsalarylakhs.Add("49");
            Annualsalarylakhs.Add("50");
            ViewBag.Annualsalarylakhs1 = Annualsalarylakhs;
        }

        public void GetAnnualSalaryThousands()
        {
            List<string> AnnualSalaryThousands = new List<string>();
            AnnualSalaryThousands.Add("10000");
            AnnualSalaryThousands.Add("20000");
            AnnualSalaryThousands.Add("30000");
            AnnualSalaryThousands.Add("40000");
            AnnualSalaryThousands.Add("50000");
            AnnualSalaryThousands.Add("60000");
            AnnualSalaryThousands.Add("70000");
            AnnualSalaryThousands.Add("80000");
            AnnualSalaryThousands.Add("90000");
            ViewBag.AnnualSalaryThousands1 = AnnualSalaryThousands;
        }

Please help me anyone……..

Thanks in advance………..

Hi Madhavaram,

For this requirement, it is similar to the cascading DropDown list. Please refer to this link below to achieve that:

# Cascading Dropdown List With MVC, LINQ to SQL and AJAX

http://www.codeproject.com/Articles/730953/Cascading-Dropdown-List-With-MVC-LINQ-to-SQL-and-A

Best Regards

Starain

Am not able to solve it using this article……..can u solve it by using this

these are my two methods that am using in the controller  and binding to return to the view…….

 public void GetAnnualsalarylakhs()
        {
            List<string> Annualsalarylakhs = new List<string>();
            Annualsalarylakhs.Add("<0.5");
            Annualsalarylakhs.Add("1");
            Annualsalarylakhs.Add("2");
            Annualsalarylakhs.Add("3");
            Annualsalarylakhs.Add("4");
            Annualsalarylakhs.Add("5");
            Annualsalarylakhs.Add("6");
            Annualsalarylakhs.Add("7");
            Annualsalarylakhs.Add("8");
            Annualsalarylakhs.Add("9");
            Annualsalarylakhs.Add("10");
            Annualsalarylakhs.Add("11");
            Annualsalarylakhs.Add("12");
            Annualsalarylakhs.Add("13");
            Annualsalarylakhs.Add("14");
            Annualsalarylakhs.Add("15");
            Annualsalarylakhs.Add("16");
            Annualsalarylakhs.Add("17");
            Annualsalarylakhs.Add("18");
            Annualsalarylakhs.Add("19");
            Annualsalarylakhs.Add("20");
            Annualsalarylakhs.Add("21");
            Annualsalarylakhs.Add("22");
            Annualsalarylakhs.Add("23");
            Annualsalarylakhs.Add("24");
            Annualsalarylakhs.Add("25");
            Annualsalarylakhs.Add("26");
            Annualsalarylakhs.Add("27");
            Annualsalarylakhs.Add("28");
            Annualsalarylakhs.Add("29");
            Annualsalarylakhs.Add("30");
            Annualsalarylakhs.Add("31");
            Annualsalarylakhs.Add("32");
            Annualsalarylakhs.Add("33");
            Annualsalarylakhs.Add("34");
            Annualsalarylakhs.Add("35");
            Annualsalarylakhs.Add("36");
            Annualsalarylakhs.Add("37");
            Annualsalarylakhs.Add("38");
            Annualsalarylakhs.Add("39");
            Annualsalarylakhs.Add("40");
            Annualsalarylakhs.Add("41");
            Annualsalarylakhs.Add("42");
            Annualsalarylakhs.Add("43");
            Annualsalarylakhs.Add("44");
            Annualsalarylakhs.Add("45");
            Annualsalarylakhs.Add("46");
            Annualsalarylakhs.Add("47");
            Annualsalarylakhs.Add("48");
            Annualsalarylakhs.Add("49");
            Annualsalarylakhs.Add("50");
            ViewBag.Annualsalarylakhs1 = Annualsalarylakhs;
        }

        public void GetAnnualSalaryThousands()
        {
            List<string> AnnualSalaryThousands = new List<string>();
            AnnualSalaryThousands.Add("10000");
            AnnualSalaryThousands.Add("20000");
            AnnualSalaryThousands.Add("30000");
            AnnualSalaryThousands.Add("40000");
            AnnualSalaryThousands.Add("50000");
            AnnualSalaryThousands.Add("60000");
            AnnualSalaryThousands.Add("70000");
            AnnualSalaryThousands.Add("80000");
            AnnualSalaryThousands.Add("90000");
            ViewBag.AnnualSalaryThousands1 = AnnualSalaryThousands;
        }

 [HttpGet]
        public ActionResult CompanyVacancy()
        {

           
            GetAnnualsalarylakhs();
            GetAnnualSalaryThousands();
            GetState();
            return View();
        }

this is the view 

<dl>
<dt>Annual salary</dt>
<dd> <%= Html.DropDownListFor(model => model.AnnualSalary.MinimumLakhs, new SelectList(ViewBag.Annualsalarylakhs1),"Lakhs",new {style="display:inline; width:90px;",@id="txtMinimumLakhs",@class="mid-size mr10",@placeholder="Laks"})%>
<%= Html.DropDownListFor(model => model.AnnualSalary.MinimumThousands, new SelectList(ViewBag.AnnualSalaryThousands1),"Thousands",new {style="width:90px;",@id="txtMinimumThousands",@class="mid-size",@placeholder="Thousands"})%></dd>
<dt>&nbsp;</dt>
<dt>To</dt>
<dt>&nbsp;</dt>
<dd><%= Html.DropDownListFor(model => model.AnnualSalary.MaximumLakhs, new SelectList( ViewBag.Annualsalarylakhs1),"Lakhs",new {style="display:inline; width:90px;",@id="txtMaximumLakhs",@placeholder="Laks",@class="mid-size mr10"})%>
<%= Html.DropDownListFor(model => model.AnnualSalary.MaximumThousands, new SelectList(ViewBag.AnnualSalaryThousands1),"Thousands",new {style="display:inline; width:90px;",@id="txtMaximumThousands",@placeholder="Thousands",@class="mid-size"})%></dd>
</dl>

how to check  the condition based on minimum salary dropdown how to get the max salary dropdown values………

please help me how to get the condition………..

thanks in advance 

Hi Madhavaram,

Please modify your code like this:

 public List<string> GetAnnualsalarylakhs(string min)
        {
           List<string> Annualsalarylakhs = new List<string>();
           int minValue=1;
           if(min==null)
            {
                Annualsalarylakhs.Add("<0.5");
            }
            else
            {
               minValue=int.Parse(min);
               for(int i=minValue+1;i<50;i++)
                  {
                     Annualsalarylakhs.Add(i.ToString());
                  }

            }            
            return Annualsalarylakhs;
        }
 public List<string> GetAnnualSalaryThousands(int min=9999)
        {
            List<string> AnnualSalaryThousands = new List<string>();
            for(int i=min+1;i<90000;i+=10000)
            {
                 AnnualSalaryThousands.Add(i.ToString());
            }
            AnnualSalaryThousands.Add("10000");
            AnnualSalaryThousands.Add("20000");
            AnnualSalaryThousands.Add("30000");
            AnnualSalaryThousands.Add("40000");
            AnnualSalaryThousands.Add("50000");
            AnnualSalaryThousands.Add("60000");
            AnnualSalaryThousands.Add("70000");
            AnnualSalaryThousands.Add("80000");
            AnnualSalaryThousands.Add("90000");
            return AnnualSalaryThousands;
        }

[HttpGet]
        public ActionResult CompanyVacancy()
        {
   
           ViewBag.Annualsalarylakhs1= GetAnnualsalarylakhs();
           ViewBag.AnnualSalaryThousands1 = GetAnnualSalaryThousands();
            GetState();
            return View();
        }
$(function () {
        $("#txtMinimumLakhs").change(function () {
                 var selectedItem = $(this).val();
               var ddlMax = $("#txtMaximumLakhs");
               $.ajax({
                 cache: false,
                 type: "GET",
                 url: "@(Url.Action("GetAnnualsalarylakhs"))",
                    data: { "min": selectedItem },
                    success: function (data) {                       
                        $.each(data, function (id, option) {
                            ddlMax .append($('<option></option>').val(data).html(data));
                        });  
                    },
                    error: function (xhr, ajaxOptions, thrownError) {
                        alert('Failed to retrieve states.'); 
                    }
                });
            });
        });
     </script> 

Note: This is just a simple and part code, you need modify it.

Best Regards

Starain

Try  this

    $(document).ready(function () {
        $("#AnnualSalary_MinimumLakhs").change(function () {
            var min = parseInt($(this).val());
            $("#AnnualSalary_MaximumLakhs option").each(function () {               
                $(this).remove();
            });
            $("#DaysAnnualSalary_MinimumLakhs option").each(function () {
                if (min <= parseInt($(this).val()))
                    $("#AnnualSalary_MaximumLakhs").append($(this).clone());
            });
        });
    });