Category Archives: PlaceHolder

PlaceHolder

[RESOLVED]Session key value returns null

Hi,

I do Session.Add("key", value) from a controler, but when i post a form session["key"] returns null?

Session mode in web.config is SQLServer. Timeout is default value – 20 minutes. What’s wrong?

Nobody knows?

i’m trying to save a confirmation code when a user register. May be another way exists?

Ever tried?:

Session["key"] = value

Does the code work if you use InProc for session?  If so it is probably that your session config isn’t properly setup for use SQL as storage.

I do this:

if (Session["key"] == null)
{
   var key = (new Random()).Next(100000, 999999);
   Session.Add("key", key);
   return View(registerView);
}

I post my form twice

In the first case i set a key. In the second case i check a key which should not be null but is

No, InProc doesn’t work, that’s why i try to use SQLServer.

If I look in the database, i can see an item for my test session

Where are you reading the session?

I set a value in c# code and send the form to the client. User entering a confirmation key and post the form again. In controller I want to check key, to do this I need get a key from the session and compare with the entered key but session["key"] is null

By the way if i write:

    <div class="middle">
        <div class="form-input form-input-confirm-key">
            @Html.TextBox("_ConfirmKey", "", new {id="_ConfirmKey", placeholder = @GlobalRes.ConfirmKey })
        </div>
        <div class="help-context">
            @GlobalRes.HelpConfirmKeyMessage
        </div>
        @Session["key"]
    </div>

I can see a value on the client side

This statement in fact runs at server. So, that means, the server session worked.

@Session["key"]

so why i can’t get key value from c# code?

If it’s working in razor (which executes on serverside), the same should work in C#. Shall we know where exactly you are trying to access Session["key"] – Was it in some Controller Action?

Yes, that’s right:

[HttpPost]
public ActionResult Register(RegisterView registerView)
{
    if (ModelState.IsValid)
    {
        if (Session["key"] == null)
        {
            var key = (new Random()).Next(100000, 999999);
            Session.Add("key", key);
            return View(registerView);
        }

        // TODO: Check a confirmation key
        // TODO: Add a database user item

        return RedirectToAction("Index", "Profile");
    }

    return View(registerView);
}

BrockAllen once pinpointed me to this, after I asked him a question about Session[]:

http://brockallen.com/2012/04/07/think-twice-about-using-session-state/

Could save you some trouble.

I know that InProc mode is awful. That’s why i use SQL Server mode.

I need to save confirmation key which can’t be cached or stored on the client side cause of safety

sameness

[HttpPost]
public ActionResult Register(RegisterView registerView)
{
    if (ModelState.IsValid)
    {
        if (Session["key"] == null)
        {
            var key = (new Random()).Next(100000, 999999);
            Session.Add("key", key);
            return View(registerView);
        }

        // TODO: Check a confirmation key
        // TODO: Add a database user item

        return RedirectToAction("Index", "Profile");
    }

    return View(registerView);
}

Are you sure setting the session key should be in that HttpPost action - shouldn’t it be in a HttpGet action? They way you have it now will display the page again after posting, because it wasn’t set yet.

I’m sure. At first I need check a model "isvalid" then create a key and return the same form with popup for confirmation key

If your model is like this    

    public class RegisterView
    {
        //other profile props
        public string ConfirmKey { get; set; }//it can also be integer
    }

Main view, make it ajax form. show that you can render partial view replace same container of current form first post for confirmation key

 [HttpPost]
        public ActionResult Register(RegisterView registerView)
        {
            if (ModelState.IsValid)
            {
                if (string.IsNullOrEmpty(registerView.ConfirmKey))
                {
                    var key = (new Random()).Next(100000, 999999);
                    Session.Add("key", key);
                }
                else
                {
                    if (registerView.ConfirmKey == Session["key"].ToString()) // TODO: Check a confirmation key
                    {
                        //Add a database user item
                        return RedirectToAction("Index", "Profile");
                    }
                    else
                    {
                        ModelState.AddModelError("", "Invalid confirmation key");
                    }
                }
               
            }

            return PartialView(registerView);
        }

[RESOLVED]Validator for HTML Helper ListBoxFor( )

Hello,

How to validate a html helper listbox using model binding ?

MODEL:

 public class ParentModel
    {        
        public FileUploadModel FileUploadModel { get; set; }
        public ProgramViewModel ProgramViewModel { get; set; }
    } 

public class FileUploadModel
    {        
        [Required, Microsoft.Web.Mvc.FileExtensions(Extensions = "jpg", ErrorMessage = "please specify a jpg file only.")]
        [DisplayName("FileName")]
        public HttpPostedFileBase File { get; set; }

        [Required(AllowEmptyStrings=false,ErrorMessage = "Please add an auxiliary state")]
        [MaxLength(100, ErrorMessage = "AuxiliaryState should not be longer than 100 characters.")]
        [DisplayName("AuxiliaryState")]
        public string AuxiliaryState { get; set; }

        public bool IsAllPrograms { get; set; }  
    }
    public class ProgramViewModel
    {        
        public IEnumerable<string> SelectedPrograms { get; set; }
        public IEnumerable<SelectListItem> Programs { get; set; }
    }

Controller:

 [HttpPost]
        public ActionResult AuxiliaryProgramMapping(ParentModel model)
        {
            if (ModelState.IsValid)
            {                
                bool isCheckedForAllPrograms =model.FileUploadModel.IsAllPrograms;
                var AuxProgramName = model.FileUploadModel.AuxiliaryState;

                IEnumerable<string> selectedPrograms = model.ProgramViewModel.SelectedPrograms;
                if (selectedPrograms == null)
                {
                       // something
                }
                else
                 {
                    StringBuilder sb = new StringBuilder();
                    sb.Append("You selected – " + string.Join(",", selectedPrograms));
                    string x = sb.ToString();
                 }



                List<SelectListItem> listSelectListItems = new List<SelectListItem>();
                List<AdminDTO> lll = objAdminBussinessLayer.GetActivePrograms();
                foreach (var programs in lll)
                {
                    SelectListItem selectList = new SelectListItem()
                    {
                        Text = programs.ProgramName,
                        Value = Convert.ToString(programs.ProgramID)
                    };
                    listSelectListItems.Add(selectList);
                }
                ProgramViewModel ProgramsViewModel = new ProgramViewModel()
                {
                    Programs = listSelectListItems
                };

                ParentModel parent = new ParentModel();
                parent.ProgramViewModel = ProgramsViewModel;

                string path = @"D:Temp";

                HttpPostedFileBase photoa = model.FileUploadModel.File;
                if (photoa != null)
                    photoa.SaveAs(path + photoa.FileName);
                return View(parent);

            }
            else
            {
                List<SelectListItem> listSelectListItems = new List<SelectListItem>();
                List<AdminDTO> lll = objAdminBussinessLayer.GetActivePrograms();
                foreach (var programs in lll)
                {
                    SelectListItem selectList = new SelectListItem()
                    {
                        Text = programs.ProgramName,
                        Value = Convert.ToString(programs.ProgramID)
                    };
                    listSelectListItems.Add(selectList);
                }
                ProgramViewModel ProgramsViewModel = new ProgramViewModel()
                {
                    Programs = listSelectListItems
                };

                ParentModel parent = new ParentModel();
                parent.ProgramViewModel = ProgramsViewModel;
                return View(parent);
            }
        }

VIEW:

@using (Html.BeginForm("AuxiliaryProgramMapping", "AuxiliaryProgramMapping", FormMethod.Post, new { enctype = "multipart/form-data" }))
            {
               ... blah blah 

 @Html.ListBoxFor(model => model.ProgramViewModel.SelectedPrograms, Model.ProgramViewModel.Programs, new { @class = "select2-me input-block-level",@size="10", data_placeholder = "Select one or more program(s)."})
                               
 @* Now how to validate this listbox .. (required)*@
               ... blah blah
             }

 

Hi did you try  this ?

@Html.ValidationMessageFor(model => model.YourModel, "", new { @class = "text-danger" })

i would gladly do that , but the problem is WHERE shall i mention the Required attribute ?

i did like below : but couldnt make it work.

 public class ProgramViewModel
    {
        [Required(ErrorMessage = "Please select atleast one program")]
        public IEnumerable<string> SelectedPrograms { get; set; }
        public IEnumerable<SelectListItem> Programs { get; set; }
    }


 @Html.ListBoxFor(model => model.ProgramViewModel.SelectedPrograms, Model.ProgramViewModel.Programs, new { @class = "select2-me input-block-level",@size="10", data_placeholder = "Select one or more program(s)."})
 @Html.ValidationMessageFor(model => model.ProgramViewModel.SelectedPrograms) 

to make it easy why don’t you just try to use this?

http://jqueryvalidation.org/required-method/ 

M afraid i cant do that , requirement is like this only , i cant do validations from jquery i need to do that using model binding only.

Anyone ???

Hi Ashim,

For this requirement, you need to custom validation.

There are some links that can help you:

# Custom Unobtrusive jQuery Validation with Data Annotations

http://thewayofcode.wordpress.com/2012/01/18/custom-unobtrusive-jquery-validation-with-data-annotations-in-mvc-3/

# Required Attribute on Generic List Property

http://stackoverflow.com/questions/6428907/required-attribute-on-generic-list-property

Best Regards

Starain

Starain chen – MSFT

# Custom Unobtrusive jQuery Validation with Data Annotations

http://thewayofcode.wordpress.com/2012/01/18/custom-unobtrusive-jquery-validation-with-data-annotations-in-mvc-3/

Thats a good example to override the isvalid method , but the the thing is m new to MVC and i really dont have any idea about how to do custom validation on a listboxfor helper ? Can you please help me out ?

# Required Attribute on Generic List Property

http://stackoverflow.com/questions/6428907/required-attribute-on-generic-list-property

This is custom validation on whether the generic list is empty or not , my question is whether the list have any selected item or not ? both are different. 

Hi Ashim,

You could refer to the first link to learn how to custom validation and the second link is the sample about how to check whether the collection is empty or not.

For the form submit, it just sends the selected items data instead of all items. So you just need to check whether the collection has data or not.

Best Regards

Starain

Starain chen – MSFT

So you just need to check whether the collection has data or not.

I tried , but its not working : see this:

MODEL:

 [AttributeUsage(AttributeTargets.Property, AllowMultiple = true)]
    public class IsSelectedAttribute : ValidationAttribute
    {
        public IsSelectedAttribute(string errorMessage) : base(errorMessage)
        {
            this.ErrorMessage = errorMessage;
        }

        protected override ValidationResult IsValid(object value, ValidationContext validationContext)
        {
            ValidationResult validationResult = ValidationResult.Success;
            try
            {
                if(value == null)
                {
                    validationResult = new ValidationResult(ErrorMessageString);
                }                
            }
            catch (Exception ex)
            {
                // Do stuff, i.e. log the exception
                // Let it go through the upper levels, something bad happened
                throw ex;
            }

            return validationResult;
        }
    }
    public class ParentModel
    {
        public AuxiliaryProgramMappingDTO AuxiliaryProgramMappingDTO { get; set; }
        public FileUploadModel FileUploadModel { get; set; }
        public ProgramViewModel ProgramViewModel { get; set; }
    }    
    public class FileUploadModel
    {        
        [Required(ErrorMessage="Please upload an icon"), Microsoft.Web.Mvc.FileExtensions(Extensions = "jpg", ErrorMessage = "please specify a jpg file only.")]
        [DisplayName("FileName")]
        public HttpPostedFileBase File { get; set; }

        [Required(AllowEmptyStrings=false,ErrorMessage = "Please add an auxiliary state")]
        [MaxLength(100, ErrorMessage = "AuxiliaryState should not be longer than 100 characters.")]
        [DisplayName("AuxiliaryState")]
        public string AuxiliaryState { get; set; }

        public bool IsAllPrograms { get; set; }
    }
    public class ProgramViewModel
    {   
        [IsSelected("Please select atleast one program.")]
        public IEnumerable<string> SelectedPrograms { get; set; }
        public IEnumerable<SelectListItem> Programs { get; set; }
    }

VIEW:

 @Html.ListBoxFor(model => model.ProgramViewModel.SelectedPrograms, Model.ProgramViewModel.Programs, new { @class = "select2-me input-block-level",@size="10", data_placeholder = "Select one or more program(s)."})
 @Html.ValidationMessageFor(model => model.ProgramViewModel.SelectedPrograms) 

After this in Controller when i try to check whether ModelState is valid.Its showing valid ,when it should not.Please recreate the scenario at your end.

Ashim Chatterjee

Html.ListBoxFor(model => model.ProgramViewModel.SelectedPrograms, Model.ProgramViewModel.Programs, new { @class = "select2-me input-block-level",@size="10", data_placeholder = "Select one or more program(s)."})
 @Html.ValidationMessageFor(model => model.ProgramViewModel.SelectedPrograms)

           Html.ListBoxFor(model => model.ProgramViewModel.SelectedPrograms, Model.ProgramViewModel.Programs, new {  required="required",@class = "select2-me input-block-level",@size="10", data_placeholder = "Select one or more program(s)."})
                @Html.ValidationMessageFor(model => model.ProgramViewModel.SelectedPrograms)

add required="required"  attribute to the listbox

cnuonline

add required="required"  attribute to the listbox

You are a life saver … cheers. 

Thanks  a lot. :)

cnuonline

add required="required"  attribute to the listbox

Just One Question : can i add my own error message instead of the default one ?

try this

document.getElementById('ProgramViewModel_SelectedPrograms').setCustomValidity('Please select  a Programs');

where shall i call that .. i tried in document ready , didnt worked .

Is this a main view or a partial view loading after document load?

this is a main view.

Make sure the id of the list box in the statement

Thanks .. :)

[RESOLVED]new to mvc – Question about HTML5

does mvc4 naitively support HTML5 can someone point me to a post that explains how to implement HTML5 with MVC everything i’ve found is from 2010.

Yes, MVC allows you to emit HTML5.

DeadTroll

does mvc4 naitively support HTML5

Yes. Could you provide a bit more detail on exactly what you are trying to do? To ensure that you are targeting HTML5, you might want to make sure that you have the appropriate HTML DOCTYPE element present within your Views / Layout :

<!DOCTYPE html>

Have a link to an example of how to accomplish it?

I have not written any code as of yet. I’m trying to research how I might accomplish it first. IE does @Html.TextBox("SearchString") render html4 or html5 textbox?

There’s no difference.

To indicate that a particular View or document will support HTML5 mark-up, you just need to use the DOCTYPE as previously shown within your Views or Layouts :

<!DOCTYPE html>
<html>
<head>
    <!-- Your Head Content -->
</head>
<body>
    <!-- Your Content -->
</body>
</html>

With regards to the HTML helpers and the markup that they generate, its going to be the same. There really isn’t a difference between an HTML5 <input> element and a HTML4 <input> element (which are both going to be generated by the Html.TextBox() helpers).

Despite what you may have heard, HTML5 isn’t exactly some revolutionary concept that will change everything. It adds support for a variety of new types of elements (such as <article>, <video>, <audio> and many, many more) but unless you are specifically
using those and taking advantage of what they can do, most things are going to be the same. The most common elements like <input>, <div>, <select> and all of the font-related styles have not really changed.

If you are interested in some of the differences in what was added within HTML5, you can see the
available W3 specification here.

Ok, I get that and thank you for the info. If I want to take advantage of input type Date or Number, is there an html helper for that? I have a use for Date, Datetime, Number, Email and tel and I’ve been looking at mvchtmlhelper
class
 and do not see anything that would target the new html5 input types

IIRC the html helpers emit the comparable type attribute based upon the model type being used. But in all honesty ifyou’re targeting HTML5 then you’re doing a lot of your work in JS and the features of the html helpers is diminished. Personally, these days,
I don’t use the html helpers anymore and I just code the HTML I need.

Almost all of the HTML Helpers support a parameter called "htmlAttributes" which can accept an anonymous object that allows you to set these specific values depending on the type of field you intend to render :

@Html.TextBox("DateTextBox","", new { type = "date" })

This would render an <input> element with the appropriate type set specified by your htmlAttributes :

<input id='DateTextBox' name='DateTextBox' type='date' />

If your browser supports the date type, then you might see something like the following :

You can see an example of this here.

BrockAllen

Personally, these days, I don’t use the html helpers anymore and I just code the HTML I need.

I’m in the same boat.

The longer that I use MVC, the more that the HTML Helpers start looking like the dreaded Web Forms Controls. This is especially true of more complex ones like the DropDownList. 

Rion Williams

BrockAllen

Personally, these days, I don’t use the html helpers anymore and I just code the HTML I need.

I’m in the same boat.

So you both code unobtrusive validation

data-val-required

 from hand?

ignatandrei

So you both code unobtrusive validation

data-val-required

 from hand?

It just depends on the scenario, but I don’t mind using the required attribute on it’s own as well as other HTML5-related things like placeholders. If I need some complex client-side validation, I’ll wire it up on my own, but besides that I generally let
MVC spit the model back out with errors (using the ValidationSummary) from the server.

ignatandrei

So you both code unobtrusive validation from hand?

This would be the feature you’d be losing, yes. But as I said, if I have that code elsewhere (or don’t need/wait it) then it feels as if the html helpers are just getting in my way.

so if you are not using the html helpers then what is your preferred method of model binding? 

Html helpers help render validation feedback to the user. I still use model binding to map request data to my action method parameters.

[RESOLVED]View doesn't post back to controller?

Hello,

I have an area inside that is a Register Controller and Register View, the controller looks like this.

   [HttpGet]
        public ActionResult Register()
        {
            var userRegister = new UserRegister();

            return View(userRegister);
        }

        [HttpPost]
        public ActionResult Register(UserRegister userRegister)
        {
            if (ModelState.IsValid)
            {
                var userProfile = new RegisterService().RegisterUser(userRegister);

                if (userProfile != null)
                {
                    new AuthenticateUser().UserLoggedIn(userProfile);

                    return RedirectToAction("UserProfile", "Profile", new { area = "Profile" });
                }
                else
                {
                    TempData["error"] = "Something went wrong with your registration, plese check the details you entered and try again";
                }
            }

            return View(userRegister);
        }

My view looks like this

  @using (Html.BeginForm("Register", "Register", FormMethod.Post))
                                    {
                                        <fieldset>
                                            <label class="block clearfix">
                                                <span class="block input-icon input-icon-right">
                                                    @Html.TextBoxFor(m => m.Firstname, new { @id = "txtFirstname", @class = "form-control", @placeholder = "Firstname" })
                                                    <i class="ace-icon fa fa-user"></i>
                                                </span>
                                            </label>

                                            <label class="block clearfix">
                                                <span class="block input-icon input-icon-right">
                                                    @Html.TextBoxFor(m => m.Surname, new { @id = "txtSurname", @class = "form-control", @placeholder = "Surname" })
                                                    <i class="ace-icon fa fa-user"></i>
                                                </span>
                                            </label>
                                            <label class="block clearfix">
                                                <span class="block input-icon input-icon-right">
                                                    @Html.TextBoxFor(m => m.EmailAddress, new { @id = "txtEmailAddress", @class = "form-control", @placeholder = "Email Address" })
                                                    <i class="ace-icon fa fa-user"></i>
                                                </span>
                                            </label>
                                            <label class="block clearfix">
                                                <span class="block input-icon input-icon-right">
                                                    @Html.TextBoxFor(m => m.Password, new { @id = "txtPassword", @class = "form-control", @placeholder = "Password", @type = "Password" })
                                                    <i class="ace-icon fa fa-lock"></i>
                                                </span>
                                            </label>
                                            <label class="block clearfix">
                                                <span class="block input-icon input-icon-right">
                                                    @Html.TextBoxFor(m => m.ConfirmPassword, new { @id = "txtConfirmPassword", @class = "form-control", @placeholder = "Confirm Password" })
                                                    <i class="ace-icon fa fa-lock"></i>
                                                </span>
                                            </label>
                                            <label class="pull-left">
                                                @*<input class="ace" type="checkbox">*@
                                                @Html.CheckBoxFor(m => m.AcceptedTerms, new { @class = "ace" })
                                                <span class="lbl"> Agree to Terms and Conditions</span>
                                            </label>
                                            <div class="clearfix">
                                                <input type="button" value="Register" class="width-35 pull-right btn btn-sm btn-primary" />

                                                @*<button type="button" class="width-35 pull-right btn btn-sm btn-primary">
                                                        <i class="ace-icon fa fa-pencil"></i>
                                                        <span class="bigger-110">Register</span>
                                                    </button>*@
                                            </div>
                                            <div class="space-4"></div>
                                        </fieldset>
                                    }

Now no maatter what i do this form does not submit to the register controlller post…….. can any one see why?

<input type="button"> doesn’t perform a post. change to type="submit".

[RESOLVED]Masking for Textboxfor Helper in MVC 4.

Hello All,

I am trying to mask a textboxfor helper of mvc 4 razor syntax using javascript.But it isnt working.Can anyone please guide me ? I want to use onkeypress kind of event so that the user can understand while typing.

@Html.TextBoxFor(model => model.AuxiliaryProgramMappingDTO[i].BreakDuration, new { id = "BreakDuration" + Model.AuxiliaryProgramMappingDTO[i].BreakTypeid.ToString(),  @placeholder = Model.AuxiliaryProgramMappingDTO[i].BreakDuration, @class = "input-medium" })

After defining the textbox in Razor, you need to invoke the javascript code. Assuming that you are using mask javascript and already include the script file in the code

$('input.input-medium').setMask({ mask: '999-999-9999' });

For more information please check this

Input
Masking in MVC 4 using Data Annotation

pprasannak

$('input.input-medium').setMask({ mask: '999-999-9999' });

Not working.No change.

Ashim Chatterjee

Not working.No change.

Please elaborate what have you done.

You need to do the following to show the masked textbox

1. In the view use the TextBoxFor helper (which you have already done)

2. Include the javascript plugin which does the masking

3. On the document load, call the mask (similar to the javascript code I provided earlier)

Also please check the link I posted earlier.

You can try using the Jquery Plugins to mask your textbox  digitalBush Masking Plugin.

Sample Code:

 <script type="text/javascript">
             jQuery(function ($) {
                 $(".input-medium").mask("999-99-9999");
             });

        </script>

[RESOLVED]Getting values from a Listbox( in PartialView) being delivered in view by Html.Action, in controller HTTP Post method

How do
I access the values of ListBox in partialview being delivered by Html.Action, in controller HTTP Post method

View

<div
class="form-horizontal"><div
class="form-group"><label
class="control-label
col-xs-2">
Worker:
</label>@Html.Action("WorkerListPartial",
"WorkerTask")</div></div>

PartialView

@model Actreve.Models.WorkersViewModel
<div class="well">
    <div class="container">
        <div class="row alert-info">
            @Html.ListBoxFor(m => m.worker, Model.WorkersList, new { size = 5, data_placeholder="Select worker.." })
            </div></div></div>
   public class WorkersViewModel
    {
      public string WorkerName { get; set; }
      public int WorkerId { get; set; }
      public IEnumerable<string> worker { get; set; }
      public  List<SelectListItem> WorkersList{get; set;}



        public WorkersViewModel()
        {
            WorkersList = new List<SelectListItem>();
        }
    }
}

Thanks for your help,

Rose :)

for the binder to work, it need to a concrete class to create an item, change

public IEnumerable<string> worker { get; set; }

to

public List<string> worker { get; set; }

Partial View not posting selected values back

Ok I pass a viewmodel to the page inside the view model consist of three classes and a class called Filter.

I have three views each have a table on but all require the same search functionality, so i decided to put the filter in a partial view.

below is how one of my controller look.

 [HttpGet]
        public ActionResult Hierarchy()
        {
            var vm = new ProjectViewModel();

            try
            {
                var userId = (int)WebSecurity.CurrentUserId;
                var isAdmin = User.IsInRole("Admin");

                vm = new ProjectViewModel
                {
                    Filter = new FilterResults(),
                    DealerHierarchy = new DealerHierarchy().GetPosition(null, null, userId, isAdmin)
                };

                vm.Filter.PaymmentStatus = new PaymentStatus().ReturnStatus(); // Build the selected Status
            }
            catch (Exception e)
            {
                Console.WriteLine(e);
            }
            return View(vm);
        }

vm.Filter is the search i.e fromDate toDate etc

below is how my view is contructed, you can see I pass down the Filter from the vm into the Partial View.

<h2>Hierarchy</h2>

@using (Html.BeginForm("Hierarchy", "Dealer", FormMethod.Post))
{
    @Html.Partial("~/Views/Shared/Filter.cshtml", @Model.Filter)
    <p>
        <button type="submit">Filter</button>
    </p>
}
<table>
    <thead>
        <tr>
            <th>Dealer Name</th>
            <th>Commission Amount</th>
        </tr>
    </thead>
    <tbody>
        @foreach (var item in Model.DealerHierarchy)
        {
            <tr>
                <td>
                    @item.DealerName
                </td>
                <td>
                    @String.Format("{0:n0}", item.CommissionAmount)
                </td>
            </tr>
        }
    </tbody>
</table>

This is the partial view

@model SomeApp.Models.FilterResults

<style type="text/css">
    .filter-container {
        width: 500px;
        margin-left: auto;
        margin-right: auto;
    }
</style>

<div class="filter-container">
  
    @Html.TextBoxFor(m => m.FromDate, new { @placeholder = "From Date", @Id = "txtFromDate" })

    @Html.TextBoxFor(m => m.ToDate, new { @placeholder = "To Date", @id = "txtToDate" })

    @Html.DropDownListFor(m => m.SelectedPaymentStatus, Model.PaymmentStatus, new { @ID = "drpPaymentStatus" })
</div>

All renders correct, but when I press Filter on the actual view it posts back but the values I have entered into the partial view aren’t passed back….

Any help?

Harrison.Scott

@using (Html.BeginForm("Hierarchy", "Dealer", FormMethod.Post))

Your filter form posts to the Hierarchy action inside the Dealer controller

Harrison.Scott

[HttpGet]
        public ActionResult Hierarchy()

But this action is defined as HttpGet. You need another Hierarchy action which accepts a post.

First of all this:

@Html.Partial("~/Views/Shared/Filter.cshtml", @Model.Filter) // @ is not needed here for before Model

should be like this:

@Html.Partial("~/Views/Shared/Filter.cshtml", Model.Filter)

You need a post action as well which will task your partial view model as parameter:

[HttpPost]
public ActionResult Hierarchy(SomeApp.Models.FilterResults model)
{

 // do something here with model posted

}
Sorry I already have a post action for the page, the controller snippet I showed above was where it was loading and populating the filter class inside the view model.

My post method expects the view model but yet filter values are null

can you show your that action here??

Harrison.Scott

My post method expects the view model but yet filter values are null

Your post method should expect ProjectViewModel as the input parameter. As Model binding is done by naming convention, your input model should be same as that of the parameters that is passed.

Best way is to view the generated html and from there determine the object that will be passed. Please post your generated html for the form.

binding counts on the name of the fields to be correct. to bind your partial view fields, they need to have the Filter. prefix (Filter.FromDate). your partial view does not know about the  prefix set so its rending the wrong field names. use:

 @Html.Partial("~/Views/Shared/Filter.cshtml") 

and use the complete model name (m=>m.Filter.FromDate) in the partial.

note: if you google you can find sample code to build a partial view that supports passing a prefix.

also if you want the partial reusable, define an IFilter interface that is just the property Filter of type FilterResults. then you can have multiple model implement the interface, and use the interface as the model type in the partial.   

Hi Bruce,

My view now looks like this

@using (Html.BeginForm("Hierarchy", "Dealer", FormMethod.Post))
{
    @Html.Partial("~/Views/Shared/Filter.cshtml", Model)
    <p>
        <button type="submit" value="Filter"></button>
    </p>
}

I have changed my partial view so it now looks like this

@model SomeApplication.ViewModel.ProjectViewModel

    <style type="text/css">
        .filter-container {
            width: 500px;
            margin-left: auto;
            margin-right: auto;
        }
    </style>

    <div class="filter-container">

        @Html.TextBoxFor(m => m.Filter.FromDate, new { @placeholder = "From Date", @Id = "txtFromDate" })

        @Html.TextBoxFor(m => m.Filter.ToDate, new { @placeholder = "To Date", @id = "txtToDate" })

        @Html.DropDownListFor(m => m.Filter.SelectedPaymentStatus, Model.Filter.PaymmentStatus, new { @ID = "drpPaymentStatus" })
    </div>

my controller

 [HttpPost]
        public ActionResult Hierarchy(ProjectViewModel vm)
        {

            DateTime? fromDate = vm.Filter.FromDate;

            return View(vm);
        }

yet my values are still null unless I have missed something?

MVC 4 validation

I have setup validation in the Model and on the Front end, I have added the necessary scripts, I have triple checked this.

I am not using the Razor View engine but .aspx view.

My textboxes I am trying to validate are TextBoxFor and than I have the ValidateMessageFor.

I have verified the web.config files and added this to the Global.asax file

   HtmlHelper.UnobtrusiveJavaScriptEnabled = true;
            HtmlHelper.ClientValidationEnabled = true;

I am using Kendo UI and I went through all there steps here http://docs.telerik.com/kendo-ui/aspnet-mvc/validation.

Validation still isn’t working?

Are there any Code examples for this?

I tried plain UI input text boxes and used the Required attribute and these didn’t work.

I need to use the Model so this isn’t practical.

Post your model code, let us see so that we can help you out.

 
HTML elements below.

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

<div class="cc">
                    <label>Cc Email Address(es)
                     <%: Html.TextBoxFor(m => m.EmailCC, new { id ="emailCC"} )%>
                        <%: Html.ValidationMessageFor(m => m.EmailCC)%>
                    </label>
                </div>

                <div class="subject">
                    <label>Email Subject                        
                        <%: Html.TextBoxFor(m => m.EmailSubject, new { id = "ecardSubject" }) %>
                        <%: Html.ValidationMessageFor(m => m.EmailSubject) %>
                    </label>
                </div>
</asp:Content>

Validation is setup in the model with a required attribute.

Scripts

<asp:Content ID="Content4" ContentPlaceHolderID="ScriptsSection" runat="server">

    <script src="../../Scripts/jquery-1.8.2.js"></script>
    <script src="../../Scripts/jquery.validate.js"></script>

<script src="../../Scripts/jquery.validate.unobtrusive.js"></script>
</asp:Content>

Does the back end validation work. Remember they are two kinds of validation. Front end and back end. Kindly state the one that is not working.

Your code looks right. still trying to figure out what the problem is

We are trying to do front end validation.

Hi,

Please use the develop tool to check whether these JS files are loaded correctly.

On the other hand, please share the project on the OneDrive, we will check it.

Best Regards

Starain

One Drive? What code did you want to see? the html and the back end?

Hi,

Base on the code, I don’t fine any issue.

Please try it in a new project. If you could reproduce that issue, share this project on the OneDrive.

Best Regards

Starain

[RESOLVED]How to add the Bootstrap design in Mvc application with example ?..

Hi friends ,

                  How to add the bootstrap design into my mvc application. Guide me with  example code. where should use the bootstrap ..

Thanks in advance,

Karthik K

 

1. MVC5 has already bootstrap

2. If you are not programming in MVC 5, then add the css and js files. 

Hi Karthik,

                  By default mvc template contains bootstrap css and javascript files. In addition _Layout (Master page) contains reference for bootstrap. So you have to just use class provided by Bootstrap. for example if you want to use Textbox with Search
image button: 

 <div class="input-group custom-search-form">
     <input type="text" class="form-control" placeholder="Search...">
     <span class="input-group-btn">
        <button class="btn btn-default" type="button">
         <i class="glyphicon glyphicon-search"></i>
        </button>
     </span>
</div>

If bootstrap is not available with your mvc template, then you can install Nuget package from Package Manager console:

Install-Package bootstrap

Now you have to add reference to bootstrap in your view/_Layout then you can start using bootstrap css classes and javascript libraries.

Thanks,

Avishek

Mark as Answer, if it helps you.

Karthik Che

How to add the bootstrap design into my mvc application

As igna said, MVC5 templates contains bootstap by default. But the older version don’t include it by default.

However you can just download it from
here
. and include it your MVC application.

For better understanding about Bootstrap i suggest you go with the below URL, which contains 6 sessions (from begining to advanced). I have also learnt from here thats why i suggest you the below video url:

http://channel9.msdn.com/Series/Building-Responsive-UI-with-Bootstrap/01

Apart from this, you can find some examples of the bootstrap components here:

http://getbootstrap.com/components/#pagination

 

[RESOLVED]After updating from VS2012 to VS2013, CS1061 compile error

For my MVC 4 web application, I updated 3 machines from VS2012 to VS2013, applied VS2013.4 update, ran NuGet> Install-Package Microsoft.AspNet.Mvc -Version 4.0.40804.0 -Project (project name).

The solution rebuilds with no errors.

But when I run the web site in IISExpress under the debugger, on two of the machines I get a compile error in the browser that comes up:

Compiler Error Message: CS1061: ‘object’ does not contain a definition for ‘SubMenuItem’ and no extension method ‘SubMenuItem’ accepting a first argument of type ‘object’ could be found (are you missing a using directive or an assembly reference?)

Source Error:
Line 3:  <asp:Content ID="Content1" ContentPlaceHolderID="TitleContent" runat="server">
Line 4:      <%= this.S("JTLanguage") %> – <%= this.S(Model.SubMenuItem) %>
Line 5:  </asp:Content>

The page header is:

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

It seems that it can’t find my model class (TextViewData), though it’s namespace is referenced in the namespaces list in the"Web.config file.

If it right-click on "Model" and select "Go to definition", it brings up the non-generic ViewPage class, and not the generic version.

Any ideas on how to fix this?

Thanks.

-John

Upgrading from MVC 4.0.0.1 to 5.2.2.0 seems to have fixed it.  I initially resisted upgrading as I thought it would require lots of changes to my 100′s of views, but apparently not.  See

https://www.asp.net/mvc/overview/releases/how-to-upgrade-an-aspnet-mvc-4-and-web-api-project-to-aspnet-mvc-5-and-web-api-2