Registering DbContext in ASP.NET MVC Application as InstancePerRequest. (IoC Autofac)

builder.RegisterType<ADbContext>().As<IADbContext>().InstancePerRequest();

Using inside BService

public class BService : IBService
{
    readonly IADbContext _dbContext;
    public BService(IADbContext dbContext)
    {
        _dbContext = dbContext;
    }
}

Trying to register IBService as Singleton.

builder.RegisterType<BService>().As<IBService>().SingleInstance();

Obviously, this gives me an error

No scope with a tag matching 'AutofacWebRequest' is visible from the scope in which the instance was requested.

Simplest solution is to register IBService as InstancePerRequest, but there is no reason having PerRequest IBService rather than error message mentioned above.

How can i use PerRequest DbContext inside Singleton service ?

I'm executing same command in every 2 seconds. I think following code creates multiple connections:

[System.Web.Services.WebMethod]
public static int getActivity()
{
    using (SqlConnection connection = new SqlConnection(ConfigurationManager.ConnectionStrings["dbconnection"].ToString()))
    {
        connection.Open();
        using (var cmd = new SqlCommand("SELECT TOP 1 ValueX FROM TABLE WHERE ID= 2 AND EVENTID = 2 ORDER BY DATE DESC", connection))
        {
            var x = cmd.ExecuteScalar();
            int Result;

            if (x != null)
            {
                Result = int.Parse(x.ToString());
                Console.WriteLine("USER ACTIVITY : " + Result);
            }
            else
            {
                Result = -999;
            }
            connection.Close();
            return Result;
        }
    }
}

If I call this method several time Does following code make multi connection Or single connection ?

 using (SqlConnection connection = new SqlConnection(ConfigurationManager.ConnectionStrings["dbconnection"].ToString()))

Can someone explain whether I need to modify this code or Is this good one ?

Thanks.

I have three Excel Workbooks such as WorkBookA, WorkBookB and WorkBookC. Each workbook which has one sheet such as SheetA, SheetB and SheetC.

I want to create a new excel file with SheetA from WorkBookA, SheetB from WorkBookB and SheetC from WorkBookC.

How to do this? Any suggestions..?

I have web app project and an angular 2 project. I would like use SignalR to send message from the server. Then I found this article about implementing it. But I don't know how to send message to the current user.

Code for send message C#:

public class EventHub : Hub
    {
        public async Task Subscribe(string channel)
        {
            await Groups.Add(Context.ConnectionId, channel);

            var @event = new ChannelEvent
            {
                Name = $"{Context.ConnectionId} subscribed",
                Data = new
                {
                    Context.ConnectionId,
                    ChannelName = channel
                }
            };

            await Publish(@event);
        }

        public async Task Unsubscribe(string channel)
        {
            await Groups.Remove(Context.ConnectionId, channel);

            var @event = new ChannelEvent
            {
                Name = $"{Context.ConnectionId} unsubscribed",
                Data = new
                {
                    Context.ConnectionId,
                    ChannelName = channel
                }
            };

            await Publish(@event);
        }

        public Task Publish(ChannelEvent channelEvent)
        {
            Clients.Caller.OnEvent(Constants.AdminChannel, channelEvent);

            return Task.FromResult(0);
        }

        public override Task OnConnected()
        {
            var @event = new ChannelEvent
            {
                Name = $"{Context.ConnectionId} connected",
                Data = new
                {
                    Context.ConnectionId,
                }
            };

            Publish(@event);

            return base.OnConnected();
        }

        public override Task OnDisconnected(bool stopCalled)
        {
            var @event = new ChannelEvent
            {
                Name = $"{Context.ConnectionId} disconnected",
                Data = new
                {
                    Context.ConnectionId,
                }
            };

            Publish(@event);

            return base.OnDisconnected(stopCalled);
        }
    }

public static class Constants
    {
        public const string AdminChannel = "admin";
        public const string TaskChannel = "tasks";
    }

public class ChannelEvent
    {
        public string Name { get; set; }

        public string ChannelName { get; set; }

        public DateTimeOffset Timestamp { get; set; }

        public object Data
        {
            get { return _data; }
            set
            {
                _data = value;
                Json = JsonConvert.SerializeObject(_data);
            }
        }
        private object _data;

        public string Json { get; private set; }

        public ChannelEvent()
        {
            Timestamp = DateTimeOffset.Now;
        }
    }

Then in my controller I create IhubContent

private readonly IHubContext _context = GlobalHost.ConnectionManager.GetHubContext<EventHub>();

and invoke my publish event:

private void PublishEvent(string eventName, StatusModel status)
{
    _context.Clients.Group(Constants.TaskChannel).OnEvent(Constants.TaskChannel, new ChannelEvent
    {
        ChannelName = Constants.TaskChannel,
        Name = eventName,
        Data = status
    });
}

But this message sent to all users. Help me to fix this issue and implement code to the send message to the current user.

I have developed a c# WPF application which communicate to Backhoff plc through TwinCat.Ads library. I want to develop a web application which contains few features of my WPF application. Please help me how can I develop a web application that read/write Backhoff plc variables over the internet.

I just got thrown onto an ASP.NET MVC project and was tasked with making an "Offline" page that shows up whenever a flag in the database is set to true. I check the value, and if it is true, I want the whole site to be offline for any request. I made an ActionFilter to the end and add it to all requests. Then, when a page is requested, I filter accordingly. However, this also filters the Offline page itself, so I made a line that checks to see if it is the Offline page - if so, it just returns. The problem is that the login page is forwarding like so: /Account/Login?ReturnUrl=%2FOffline, which ends up showing the login page. How can I fix this problem?

public class DownForMaintenanceActionFilter : ActionFilterAttribute, IActionFilter
    {
        public DownForMaintenanceActionFilter()
        {
        }

        void IActionFilter.OnActionExecuting(ActionExecutingContext filterContext)
        {
            // If they are actually visiting the Offline page already, abort.
            if (HttpContext.Current.Request.RawUrl.Contains("Offline"))
            {
                this.OnActionExecuting(filterContext);
                return;
            }

            // We want to go to the "Down For Maintenance" Page if any of the following is true:
            bool siteIsUp = true;

            // Some other code here that sets siteIsUp = false

            if (!siteIsUp)
                RedirectToMaintenancePage(filterContext);
            else
                this.OnActionExecuting(filterContext);
        }


        private void RedirectToMaintenancePage(ActionExecutingContext filterContext)
        {
            filterContext.Result = new RedirectToRouteResult(
                new RouteValueDictionary 
                { 
                    { "controller", "Offline" }, 
                    { "action", "Index" } 
                });
        }
    }

How can I do what I want to do? Is this the best approach? Also: How can I prevent a user from visiting this page when the site isn't down? Thanks!

I have an MVC 4 partial view containing a couple of dropdown lists but when I am using this partial view in index and other pages its asking me for view bag setting for dropdown source data. My question is that can I have a partial view which will have all the dependent data loaded from its own controller and I need not to worry about the data sources population in all the ten pages where I am using it. So please advise.

I have a ASP.NET MVC application with jquery.

I have already used so many things like

<script src="~/Scripts/jquery.disable.autocomplete.min.js"></script>
$('input').disableAutocomplete();
$('input[type="password"],input[type="text"],form').disableAutocomplete();
$("input:text,form").attr("autocomplete", "off");
$("form")[0].reset();
<form id="edit-profile-form-desktop" autocomplete="off">
@Html.TextBoxFor(p => p.FirstName, new { @placeholder = "first name ", @class = "form-control", autocomplete = "test", autocompletetype = "disabled" })
@Html.TextBoxFor(p => p.LastName, new { @placeholder = "last name ", @class = "form-control", autocomplete = "off", autocompletetype = "disabled" })

After trying all these options, I am still getting prefilled texboxes in my add/edit page and biggest problem is I am getting inappropriate/previous data for edit page.

What would do I here to disable autocomplete by jQuery/HTML or backend programming?

Mainly, I am mainly facing this in mobile phones.

We have a asp.net application built in .net framework 2.0. I need to edit a web report and add few columns to the report. I updated the aspx.cs file and uploaded it to the server but there is no change in the report. If I change aspx file it works but aspx.cs file changes are not reflecting on the server. And I dont have local setup of the application to check. Is it necessary to compile the file, but same thing I have done with framework 4.5 without compiling and it worked. How can I update the report without compiling the file.

I develop a web app that use Twilio. My company product is advanced home alarm system. My mission is to handle report that getting to my web app from the alarm system and made outgoing voice phone calls to client's home using Twilio API. I read the example about TaskRouter in Twilio website that use the component like: Wokspace, TaskQueue, task, worker .. and I wonder If I need to use this components too. The TaskRouter flow is go like this: Customer number-->Twilio Number---> Worker number. I need this flow: (just outbound call) Twilio -> customer. I have a doubts if I need to use this components for that task.. I understand the worker is sort like an agent and TaskRouter perform bridge between the caller and the worker. I don't need an incoming calls just wanna perform outgoing calls when event getting to my site but i want to understand if i need to use worker that will have voice instruction to read them to the client when the phone call made? tnx

I have a xml like below

<ProcessInvoice>
  <ApplicationArea>
    <CreationDateTime>2016-06-01 13:15:36</CreationDateTime>
    <ApplicationGroup>BBEX</ApplicationGroup>
    <MessageType>PROCESSINVOICE</MessageType>
  </ApplicationArea>
</ProcessInvoice>

Now I have path and value to add, but it is dynamic. It can be like following

path-/ProcessInvoice/ApplicationArea/UserArea/Sample1 
value-001

path-/ProcessInvoice/ApplicationArea/UserArea/UserAreaLine/Sample1 
value-002

if the path is present then i have to add the value, else modify the value.

I can split the path and loop through to find till what node is present and what i have to add but I think there might be more elegant way of doing this.Please help me with the best approach to solve this?

Edit Note- I will prefer XDocument And XElement.

May be I didnt explain properly. My xml and node path both are dynamic. There might be situation where multiple nodes are missing from my xml. Now problem is i need to identify upto which node is existing in xml and which nodes i need to create.

Thanks

I want to bind only Table Columns to CheckBoxList and then selected columns should be displayed in GridView...

In my web application, i am trying to do show the selected items as comma separated in the Multi select drop down text field is it possible to do and how can i do this can any one tell me. sample image is link [As Shown in figure]

I tried:

.aspx:

<asp:DropDownCheckBoxes ID="dropdown1" runat="server" UseSelectAllNode="true" UseButtons="true" OnSelectedIndexChanged="dropdown1_SelectedIndexChanged" AutoPostBack="true"><Style DropDownBoxBoxWidth="200"/></asp:DropDownCheckBoxes>

.CS

      public void ddlsbind()
    {
    string str=string.Empty;
                string query = "select distinct col1 from Collection where sample='" + ddl2.SelectedItem.Text.ToString() + "' and col1 IS NOT NULL";            
 SqlCommand cmd = new SqlCommand(query, con);
                DataTable dt = new DataTable();
                SqlDataAdapter da = new SqlDataAdapter(cmd);
                da.Fill(dt);        
                ddlInsurance.DataSource = dt;
                ddlInsurance.DataTextField = "col1";
                ddlInsurance.DataValueField = "col1";
                ddlInsurance.DataBind();
    }

Can anyone help me to how to do this.
Thank you

I am trying to insert my rating form to the DB based up on click submitform button but I am getting the following error.

Compiler Error Message: CS0123: No overload for 'sendbtnSubmit' matches delegate 'System.EventHandler'

 /**********kgis.aspx*************/
<%@ Page Language="C#" AutoEventWireup="true" CodeBehind="kgis.aspx.cs" Inherits="portal.kgis" %>
    <%@ Register Assembly="AjaxControlToolkit" Namespace="AjaxControlToolkit" TagPrefix="asp" %>
    <!DOCTYPE html>
   <html xmlns="http://www.w3.org/1999/xhtml">
    <head runat="server">
    <style>
    .ratingStar
            {
                font-size: 0pt;
                width: 13px;
                height: 12px;          
                cursor: pointer;
                display: block;
                background-repeat: no-repeat;
            }
            .filledStar
            {
                background-image: url(images/Filled_Star.png);
            }
            .emptyStar
            {
                background-image: url(images/Empty_Star.png);
            }
            .savedStar
            {
                background-image: url(images/Saved_Star.png);
            }
            .auto-style1 {
                height: 50px;
            }
    </style>
    </head>
    <body class="hold-transition skin-blue sidebar-mini">
     <div id="popupContact">
                    <!-- Contact Us Form -->
                    <form action="#" id="feed" method="post" name="form" runat="server">

                        <h2>FeedBack</h2>
                        <hr />
                         <asp:ToolkitScriptManager ID="ToolkitScriptManager1" runat="server">  </asp:ToolkitScriptManager>




                        <table style="width: 60%;">

                            <tr>
                                <td style="font-weight: bold; padding-top: 1px;">
                                    <asp:Label ID="Label1" runat="server" Text="Name"></asp:Label>
                                </td>
                                <td>
                                    <asp:TextBox ID="name" runat="server"></asp:TextBox>
                                </td>
                            </tr>
                            <tr>
                                <td style="font-weight: bold; padding-top: 12px;">
                                    <asp:Label ID="Label2" runat="please can anyone help me on this i want to to store the rating to databse after clicking submit (onclick) form..server" Text="E-Mail"></asp:Label>
                                </td>
                                <td>
                                    <asp:TextBox ID="email" runat="server"></asp:TextBox>
                                    <asp:RegularExpressionValidator ID="RegularExpressionValidator1" runat="server" forecolor="red" ValidationExpression="\w+([-+.']\w+)*@\w+([-.]\w+)*\.\w+([-.]\w+)*" ControlToValidate="email" ErrorMessage="Input valid email!"></asp:RegularExpressionValidator>
                                </td>
                            </tr>
                            <tr>
                                <td style="font-weight: bold; padding-top: 28px;">
                                    <asp:Label ID="Label3" runat="server" Text="Area"></asp:Label>
                                </td>
                                <td>
                                    <div class="drop1">
                                        <asp:DropDownList runat="server" ID="ddlfields">
                                            <asp:ListItem Value="-1">--Select--</asp:ListItem>
                                            <asp:ListItem Value="gui">GUI</asp:ListItem>
                                            <asp:ListItem Value="coc">Correctness Of Content</asp:ListItem>
                                            <asp:ListItem Value="sug">Suggestions</asp:ListItem>
                                            <asp:ListItem Value="new">New Requirements</asp:ListItem>
                                            <asp:ListItem T Value="efs">Existing Functionality Status</asp:ListItem>
                                        </asp:DropDownList>
                                    </div>
                                </td>
                            </tr>
                            <tr>
                                <td style="font-weight: bold; padding-top: 28px;">
                                    <asp:Label ID="Label6" runat="server" Text="Category"></asp:Label>
                                </td>
                                <td>
                                    <div class="drop">
                                        <asp:DropDownList runat="server" ID="cate">
                                            <asp:ListItem Value="-1">--Select--</asp:ListItem>
                                            <asp:ListItem Value="Hostel">Hostel </asp:ListItem>
                                            <asp:ListItem Value="School">School</asp:ListItem>
                                            <asp:ListItem Value="Backwardclass">Backwardclass</asp:ListItem>
                                        </asp:DropDownList>
                                    </div>
                                </td>
                            </tr>
                            <tr>
                                <td style="font-weight: bold;">
                                    <asp:Label ID="Label4" runat="server" Text="Feedback"></asp:Label>
                                </td>
                                <td>
                                    <asp:TextBox ID="msg" runat="server" TextMode="MultiLine"></asp:TextBox>
                                </td>
                            </tr>
                            <tr>
                                <td>
                                    <asp:Label ID="Label5" runat="server" Text="Rating"></asp:Label>
                                    </td>
                                <td>
                                    <asp:Rating ID="Rating1" runat="server" StarCssClass="ratingStar" WaitingStarCssClass="savedStar"
                                        FilledStarCssClass="filledStar" EmptyStarCssClass="emptyStar" AutoPostBack="true"  MaxRating="5"
                        onchange="Rating1_Changed"                >
                                    </asp:Rating>
                                </td>
                            </tr>
                            <tr>
                                <td >
                                    <asp:Label ID="lbl_point" runat="server"></asp:Label>
                                </td>
                            </tr>

                        </table>
                        <asp:Button ID="submit" runat="server" OnClick="sendbtnSubmit" Text="Send" />

         </form>
                </div>
    </body>
    </html>

    /************kgis.aspx.cs**********************/

    using System.Data.SqlClient;
using AjaxControlToolkit;
  namespace portal
    {
        public partial class kgis : System.Web.UI.Page
        {
            protected void Page_Load(object sender, EventArgs e)
            {

            }

            protected void sendbtnSubmit(object sender,AjaxControlToolkit.RatingEventArgs e)
            {
     string connectionString = "Server=KSRSAC-G2G\\SQLEXPRESS;Database=Registration;Uid=sa;Pwd=SA#123;";
                using (SqlConnection connection = new SqlConnection(connectionString))
                {
                    SqlCommand cmd = new SqlCommand("INSERT INTO [Registration].[dbo].[FeedBack] (Name,Emailid,Category,Feedback,Area,Rate) VALUES (@Name, @Emailid,@Category,@Feedback,@Area,@Rate)");
                    cmd.CommandType = CommandType.Text;
                    cmd.Connection = connection;
                    cmd.Parameters.AddWithValue("@Name", name.Text);
                    cmd.Parameters.AddWithValue("@Emailid", email.Text);
                    cmd.Parameters.AddWithValue("@Category", cate.Text);
                    cmd.Parameters.AddWithValue("@Feedback", msg.Text);
                    cmd.Parameters.AddWithValue("@Area", ddlfields.Text);
                    cmd.Parameters.AddWithValue("@Rate", e.Value.ToString());
                    connection.Open();
                    cmd.ExecuteNonQuery();
         }
    }
    protected void Rating1_Changed(object sender, AjaxControlToolkit.RatingEventArgs e)
            {
                lbl_point.Text = "You rated " + e.Value.ToString();
            }

        }
    }

please can anyone help me on this i want to to store the rating to database after clicking submit form using asp.net C#.. Thanks in Advance

When I use autocompletion in VisualStuio2010 within my .aspx application, there are different default completions at closing control tags:

<asp:CheckBox /> 
<asp:Label></asp:Label>

Is there a explaination for this behaviour?

<asp:CheckBox></asp:CheckBox>
<asp:Label />

Wouldn't be invalid.

I have added an UserControl in GridView.

School.cs is a business object that is providing data.

ViewSchool.aspx web page

ViewSchool.aspx.cs code behind page

User control is in grid view of ViewSchool.aspx page It is not working for 2nd page. Data is properly showing on first page.

Code detail are

ViewSchool.aspx

<asp:GridView ID="GridViewSchoolDetail" runat="server" DataKeyNames="SchoolID" AutoGenerateColumns="False" ShowHeader="False" AllowPaging="True" PageSize="5"
        OnPageIndexChanging="GridViewSchoolDetail_PageIndexChanging">
        <Columns>
            <asp:TemplateField ItemStyle-Width="100%" ItemStyle-HorizontalAlign="Left">
                <ItemTemplate>
                    <schoolwebcontrol:SchoolDetail runat="server" ID="ControlSchoolDetail"
                        School_SchoolID='<%# Eval("SchoolID") %>'
                        School_SchoolCode='<%# Eval("SchoolCode") %>'
                        School_SchoolName='<%# Eval("SchoolName") %>'>
                    </schoolwebcontrol:SchoolDetail>
                </ItemTemplate>
            </asp:TemplateField>
        </Columns>
    </asp:GridView>

ViewSchool.aspx.cs

List<School> _listSchool;
protected void Page_Load(object sender, EventArgs e)
{
    if (!Page.IsPostBack)
    {
        _listSchool= School.GetInstance().GetData();

        GridViewSchoolDetail.DataSource = _listSchool;
        GridViewSchoolDetail.DataBind();
    }
}
protected void GridViewSchoolDetail_PageIndexChanging(object sender, GridViewPageEventArgs e)
{
    GridViewSchoolDetail.PageIndex = e.NewPageIndex;
    GridViewSchoolDetail.DataSource = _listSchool;
    GridViewSchoolDetail.DataBind();
}

School.cs

public class School
{
    private int _schoolID;
    public int SchoolID
    {
        get { return _schoolID; }
        set { _schoolID = value; }
    }

    private string _schoolCode = string.Empty;
    public string SchoolCode
    {
        get { return _schoolCode; }
        set { _schoolCode = value; }
    }

    private string _schoolName = string.Empty;
    public string SchoolName
    {
        get { return _schoolName; }
        set { _schoolName = value; }
    }
}

User Control

private int _school_schoolID;
public int School_SchoolID
{
    get { return _school_schoolID; }
    set { _school_schoolID = value; }
}

private string _school_schoolCode = string.Empty;
public string School_SchoolCode
{
    get { return _school_schoolCode; }
    set { _school_schoolCode = value; }
}

private string _school_schoolName = string.Empty;
public string School_SchoolName
{
    get { return _school_schoolName; }
    set { _school_schoolName = value; }
}

protected void Page_Load(object sender, EventArgs e)
{
    if (!Page.IsPostBack)
    {
        this.EnableViewState = true;

        LabelSchoolID.Text = _school_schoolID;
        LabelSchoolCode.Text = _school_schoolCode;
        LabelSchoolName.Text = _school_schoolName;
    }
}

everyone. I'm trying to build simple app that shows relations between apps and access objects. And and I have some some problems with post data.

The main idea is to show edit window with app name and multiple categorized check boxes. User will check some of them, and this info will be saved in db.

that's what i'm talking about

The promblem is how to get data from these checkboxes and put it into my model?

I got these models

public class AccessDataType
{
    public int Id { get; set; }
    public string Name { get; set; }
    public virtual IList<AccessDataParameter> AccessDataParameters { get; set; }
}

public class AccessDataParameter
{
    public int Id { get; set; }
    public string Name { get; set; }
    public virtual AccessDataType AccessDataType { get; set; }
    public virtual IList<Application> Applications { get; set; }
}

public class Application
{
    public int Id { get; set; }
    public int InternalId { get; set; }
    public string Name { get; set; }
    public virtual IList<AccessDataParameter> AccessDataParameters { get; set; }
}

I have AccessDataType that includes AccessDataParameter entries and Application class that includes some of AccessDataParameter entries.

I decided to create ApplicationAndAccessDataTypesViewModel class

public class ApplicationAndAccessDataTypesViewModel
{
    public Application Application  { get; set; }
    public IList<AccessDataType> AccessDataTypes { get; set; }
}

in my Application controller i use this method to edit my view model

    public ActionResult Edit(int id)
    {
        ApplicationAndAccessDataTypesViewModel model = new ApplicationAndAccessDataTypesViewModel
        {
            Application = dbContext.Applications.Find(id),
            AccessDataTypes = dbContext.AccessDataTypes.Include(a => a.AccessDataParameters).ToList()
        };

        return View(model);
    }

And there I have the first problem. I don't know how to create checkboxes that matches my condition. I use double for loop to print AccessDataTypes and related AccessDataParameters. For each AccessDataParameter a check box needs to be created. As I undestand, boolean value needs to be passed into CheckBoxFor/CheckBox. But my models don't have them.

  @for (int i = 0; i < Model.AccessDataTypes.Count; i++)
    {
        <div class="form-group">
            @Html.DisplayFor(model => model.AccessDataTypes[i].Name)
            <div class="col-md-offset-2 col-md-10">
                @for (int j = 0; j < Model.AccessDataTypes[i].AccessDataParameters.Count; j++)
                {
                    @Html.HiddenFor(m => Model.AccessDataTypes[i].AccessDataParameters[j].Id);
                    @Html.HiddenFor(m => Model.AccessDataTypes[i].AccessDataParameters[j].Name);
                    @Html.CheckBoxFor( -- boolean here --)
               }
            </div>
        </div>
    }

And I don't need that boolean at all. Because checkboxes must be filled using data in AccessDataParameter class. I mean checkbox AccessDataTypes[i].AccessDataParameters[j] must be checked if in AccessDataParameter in Applications property id (that comes in controller) is found.

I’m using ASP.NET Mvc 4 and ran into a conceptional problem while building a form which should allow the user to insert a complex datastructure into the Db. Consider the following datamodel:

enter image description here

Lets assume we want to create a customer (Businessrule: Each customer can have billing- and deliveryaddress but must have a default address as fallback).

The View probably would look like this:

enter image description here

The address-types were rendered as strongly-typed partialviews. I populated the Model of the partial Address-View with annotations like [Required] for Street,ZIP and Country to assure that an address will be inserted according to the underlying constraints. I render „Create-Customer“- like this… Controller:

[HttpGet]
public ActionResult CreateCustomer()
{
  var model = new CustomerModel();
  var addresses = new AddressModel[]{
    new AddressModel { AddressTypeId = 1 },//Default, required
    new AddressModel { AddressTypeId = 2 },//Billing, optional!
    new AddressModel { AddressTypeId = 3 }//Delivery, optional!
  };
  model.Addresses = addresses.ToList();
  return View(model);
}

CreateCustomer (View):

    ….Name, Number,…
  for (int i = 0; i < Model.Addresses.Count; i++)
  {
    ViewBag.CurrentAddressKindName = Model.Addresses[i].AddressKindName;    
    <fieldset>
      <legend>@ViewBag.CurrentAddressKindName</legend>
      @{Html.RenderPartial("~/Views/Address/_FormFields.cshtml", Model.Addresses[i]);}
    </fieldset>
  }
…

Now for the problem:

[HttpPost]
public ActionResult CreateCustomer(CustomerModel model)
{
  if (!ModelState.IsValid)
  {
    return BadRequest();
  }
  return Ok();
}

When posting the form back to the server, ModelState.IsValid – obviously – returns false when for instance only default- and billing-addresses are populated because of the ([Required],…) annotations in the address-model. What I want to achieve is to require (validate) the default address but ignore the validation of optional addressTypes (But only, if they are empty!) It looks like I got stuck on a conceptional problem here. Any gotchas? :D

Thanks in advance

I am trying to populate a dropdown box based on the selection of another dropdown.

I have create a sample variable var sampleData = { Default: { value1: "text", value2: "text" }, PTDR: in order to find the second dropdown populates itself once the user selects the first dropdown which seems to be working. However, I am trying to correct data from a method in my controller which I don't know how to.

any help help or guidance would be appreciated.

public ActionResult ptdrFilter(int id)
    {
        IUnitOfWork uow = DataAccess.GetUnitOfWork();
        using (ManageProductTemplate ptLogic = new ManageProductTemplate(ref uow))
        {
            List<ProductTemplate> currentpt = ptLogic.GetBy(x => x.ProductTemplateID == id);
            List<string> pt = new List<string>();
            foreach (var item in currentpt)
            {
                pt.Add(item.DistributionRule.Name);

            }
            return Json(pt);
        }
    }


    function drFilter() {

            var sampleData = { Default: { value1: "text", value2: "text" }, PTDR: { value1: "cal", value2: "cal" }, All: { value1: "lool", value2: "loool" } };
            var dataInJSONForm = JSON.stringify(sampleData);
            var datainJSObjectForm = JSON.parse(dataInJSONForm);

            $('#dd1').on('change', function (e) {
                var valueChosenInddl2 = $(this).val();
                var options = datainJSObjectForm[valueChosenInddl2];



                var $subselect = $('#subselect');
                $subselect.children().detach();
                for (var property in options) {
                    $subselect.append($('<option>', { value: property, text: options[property] }));

<div class="editor-field">
                <select id="dd1">
                  <option value="Default">Default</option>
                  <option value="PTDR">PT/DR</option>
                  <option value="All">All</option>
                </select>

<select id="ddl2">
                    <script>
                        drFilter();
                    </script>
                </select>

I am working on ASP.NET Mvc project. i have a view similar to image:

enter image description here

I design right panel in layout. my layout code:

       <div class="col-md-3 panel panel-info" style="margin-top:20px;">
        <div class="panel panel-primary" style="margin-top:8px;">
            <div class="panel-heading">Setting</div>
            <div class="panel-body">

                <div class="list-group">

                    <a href="#" class="list-group-item active text-center">Lists</a>
                    <hr />
                    <a href="#" class="list-group-item">Add Users - Partialview 1</a>

                    <a href="~/Areas/Admin/Views/Shared/_AddUser.cshtml" class="list-group-item">Edit Users - Partialview 2</a>

                    <a href="~/Areas/Admin/Views/Shared/_UserList.cshtml" class="list-group-item">User List - Partialview 3</a>

                    <a href="#" class="list-group-item">Set Password - Partialview 4</a>

                    <a href="#" class="list-group-item">User Details - Partialview 5</a>

                    <a href="#" class="list-group-item">Send Message - Partialview 6</a>

                </div>
            </div>
        </div>
    </div>

I have several modes in right panel contains : Add,Edit,List and ... Each mode has a special Partialview. I want, when i click on every mode on right panel, special partialview load in left side. how can i load dynamically partialview in asp mvc?

thanks