I have some html that I want to wrap with another tag optionally.

For instance, this would be an unread document:

<strong>
    <a href="viewDocument">
        View Document
    </a>
</strong>

And this would be a read document:

<a href="viewDocument">
    View Document
</a>

Is there an easier way to do this besides adding two @if Statements like so? This way is a bit clunky

@if(test)
{
    @:<strong>
}
    <a href="viewDocument">
        View Document
    </a>
@if(test)
{
    @:</strong>
}

I have a web form on a Razor cshtml page that needs to submit to a legacy application. The legacy application expects a <select> element with a hardcoded list of values.

That hardcoded list has changed. If I try to add a new option to this list, the legacy application will throw an error because it doesn't expect the new value.

I need to make the updated list available in the UI, and then remap the values before submitting them to the legacy application.

Her is a minimal example

<form action="/url/to/legacy.cfm method="POST">
    <select name="mylist" id="mylist_select">
        <option value="option1">Option 1</option>
        <option value="option2">Option 2</option>
        <option value="option3">Option 3</option>
        <!-- the next option can't be here when the form is posted -->
        <option value="option4">Option 4</option>
    </select>
    <input id="other" name="other_specify"/>
    <input type="submit" value="Submit"/>
</form>

I added option4. The legacy application does not expect it, and throws an error as a result. So what I need to do is when the user clicks submit but before this form gets posted, option4 needs to be removed, and the value of other needs to be set to "Option 4" as though the user just used the "Other" field on the page.

How can I do this with Razor?

MVC4 by default uses System.Web.Mvc.WebViewPage as base-class for all pages exposing properties like the helpers Html and Ajax to be used at any point in a Razor-view.

All of my Models inherit from of generic type, e.g.

MyModel : BaseModel<SomeComplexType>

Is there any chance to get something to work like

MyViewPage<TModel> : WebViewPage<TCustom> where TCustom: BaseModel<???>

to expose a property

??? MyGenericProperty { get { return Model.CustomProperty;} }

which then can be accessed like @MyGenericProperty.CustomValue in any View the same as @Html?

Adding a second parameter to MyViewPage<TModel, TCustom> : WebViewPage<TModel> does not seem to work as of each View now doesnt event know @Html or @Model.

Maybe via Reflection, Injection or some other Magic?

I am trying to send mail using GoDaddy mail server with SMTPClient in ASP.NET and my code is below , I have tried all the ports in GoDaddy but i couldn't send a mail

My code:

    try
    {

        //Mail Message
        MailMessage mM = new MailMessage();
        //Mail Address
        mM.From = new MailAddress("xxx@sender.com");
        //receiver email id
        mM.To.Add("xxx@receiver.com");
        //subject of the email
        mM.Subject = "your subject line will go here";
        mM.Body = "Body of the email";
        mM.IsBodyHtml = true;
        //SMTP client

       SmtpClient sC = new SmtpClient();

        //credentials to login in to hotmail account
        sC.Credentials = new NetworkCredential(username, password);

        //port number for Hot mail
        sC.Port = 25;
        sC.Host = "smtpout.asia.secureserver.net";
        sC.UseDefaultCredentials = false;

        //enabled SSL
        sC.EnableSsl = false;
        sC.DeliveryMethod = SmtpDeliveryMethod.Network;

        sC.Timeout = 40000;

        //Send an email
        sC.Send(mM);

    }
    catch (Exception ex)
    {
        var temp = ex.Message;
    }

I have also used port no 465 with enablessl = true but no success

In File Upload control, .HasFile returns "false" inside asp Panel but outside the Panel its "true". I have tried alot from Stack Overflow but not succeeded and I don't want to use that "trigger" (sort of) control.

I have a Ajax.BeginForm in my razor view. I want to have 3 check boxes.

  1. Begineer
  2. Intemidiate
  3. advance

checkoxes can select for any combination. When I clicked submit button bellow method in my controller will triggered.

public PartialViewResult SearchCourseCriteria(){

        var courses = from s in db.CourseCategories
                      select s;
        return PartialView("_Courses", courses);

}

This is my view

 @using (Ajax.BeginForm("SearchCourseCriteria", new AjaxOptions
    {
       UpdateTargetId = "CourseList",    
       InsertionMode = InsertionMode.Replace,  
       HttpMethod = "GET"
    }))
    {
        td>
           @Html.CheckBoxFor()                                        
        </td>

        <td>
           <input type="submit" value="Search" class="btn " />
        </td>

   }

In my model there is field called CourseLevel. I want to know How to filter courses according to the selected checkboxes. EX : If I select begineer and Intermidiate checkboex. I want to get all courseCategories from that levels. I dont know how to get that result. Help please.

I can send lat,lon, neighbors and neighborslimit variables to View.Yet, I want change neighborlimit from view. When I post View, MapViewModel's variables are 0, I have tried to ModelState.Clear() but there is no difference, Could you help me about it ? Thanks

MODEL:

public class MapViewModel
{
    public double lat;
    public double lon;
    public List<Point> neighbors;
    public Polygon polygon;

    public int neighborlimit;
    public double[][] polyTable;
}

CONTROLLER:

    [HttpGet]
    public ActionResult Map()
    {
        UserAccount user = (UserAccount)UserManager.FindByName(User.Identity.Name);
        MapViewModel model = new MapViewModel() { lat = (double)user.address.latitude, lon = (double)user.address.longitude, neighbors = user.getNeighbors(), neighborlimit= (int)user.neighborsLimit };
        return View(model);
    }

    [HttpPost]
    public ActionResult Map(MapViewModel model)
    {
       UserAccount user = (UserAccount)UserManager.FindByName(User.Identity.Name);         
       user.neighborsLimit = model.neighborlimit;
       UserManager.Update(user);
       return View(model); 
    }

VIEW:

@using (Html.BeginForm())
{
@Html.AntiForgeryToken()

    <div class="form-group">
        <div class="col-md-10">
            @Html.TextBoxFor(h => h.neighborlimit, new { @class = "form-control" })
          </div>
           <div class="col-md-offset-2 col-md-10">
                    <input type="submit" value="Log in" class="btn btn-default" />
                </div>
            </div>
}

I have a server-side model with a datetime type field PublishDate. I am sending List<Posts> as json in response to ajax call.

I would like to use c# code Convert.ToDateTime(this.PublishDate).ToString("MMM dd, yyyy") in jquery code. Below is my code what I tried so far-

var posts = response.Posts;
$.each(posts, function () {
  $('#container').append('<div class="row"> 
                            <div class="col-lg-12">
                              <h2>' + this.PostTitle + '</h2>
                              <span>Published on: @Convert.ToDateTime(this.PublishDate).ToString("MMM dd, yyyy")</span></div></div>');
});

But it's not working. Any idea?

enter image description hereI am trying to use Captcha inside my project but get a parser error with the following code...struggling to eliminate it

@{MvcCaptcha registrationCaptcha = CaptchaHelper.GetRegistrationCaptcha(); }
@if (!registrationCaptcha.IsSolved)
{
    <div class="form-group">
        <div class="col-md-offset-4 col-md-8">
            @Html.Captcha(registrationCaptcha)
        </div>
        @Html.Label("Retype the code", new { @class = "col-md-4 control-label", @for = "CaptchaCode" })
        <div class="col-md-8">
            @Html.TextBox("CaptchaCode", null, new { @class = "form-control captchaVal" })
        </div>
    </div>
}

What would the cause be of the parser error?

im getting this message/ warning

" It looks like website Signatures are switched on. This can mean that the server is identifying the type of webserver and version that it is running which can be used by a malicious user to potentially compromise this website."

how to make website signatures switched off

i tried these

<httpRuntime enableVersionHeader="false" />//in <system.web>

and

<system.webServer>
        <httpProtocol>
            <customHeaders>
                <remove name="X-AspNet-Version" />
                <remove name="X-AspNetMvc-Version" />
                <remove name="X-Powered-By" />
                <!-- <remove name="Server" />  this one doesn't work -->
            </customHeaders>
        </httpProtocol>
<system.webServer>

I have built a c#.net app for a client, which uses a sql server db as a backend. This db resides on a her company pc with ip valid. the client sometimes needs to access some data from the Internet and I built a seperate asp.net app for that purpose. asp.net app and sql server db hold on a shared host.I want sync two database(on hast and on company pc)

I want any changes to the host database and database on a pc be synchronized

i want use replication for sync two databases

So my first question:Do what you want to do is possible? Please advise me on the field. The second question : How fast can I sync the two databases

Thanks in advance for your attention.

titiry nano

I am rendering out different dates I have not reported a time for, If the time spans over more than 1 month it will render out each month and the dates under the right tab. And if the dates only is within 1 month it will only render out the dates. But my issue is when the dates are not under a tab my "Select" all checkbox doesn't work.

This is my script

    $(function () {
    $(".selectAll").on("click", function () {
        if ($(this).is(':checked')) {
            $(this).closest('.panel-default').find("input[name='isoDate']").prop('checked', this.checked);
            $('input[name="isoDate"]').trigger('change');
        } else {
            $(this).closest('.panel-default').find("input[name='isoDate']").prop('checked', false);
            $('input[name="isoDate"]').trigger('change');
        }
    });
});

And this is the view

  @if (ViewBag.MissingDays != null)
{
    int i = 0;
    var months = ((List<DateTime>)ViewBag.MissingDays).GroupBy(x => x.Month);
    IEnumerable<IGrouping<int, DateTime>> groups = months as IList<IGrouping<int, DateTime>> ?? months.ToList();
    foreach (var group in groups)
    {
        i++;
        var month = CultureInfo.CreateSpecificCulture("sv-SE").DateTimeFormat.GetMonthName(group.Key);
        if (groups.Count() > 1)
        {
            <div class="panel-group accordion" id="accordion1">
                <div class="panel panel-default">
                    <div class="panel-heading">
                        <h4 class="panel-title">
                            <a class="accordion-toggle" data-toggle="collapse" data-parent="#accordion1" href="#collapse_@i">
                                @month
                            </a>
                        </h4>
                    </div>
                    <div id="collapse_@i" class="panel-collapse collapse">
                        <div class="panel-body">
                            <div class="col-md-12">
                                <label>
                                    <input type="checkbox" class="selectAll" name="all"/>
                                    Välj alla.
                                </label>
                                <br/>
                                @foreach (var date in group)
                                {
                                    var isoDate = date.ToString("yyMMdd");
                                    var day = date.ToString("ddd", new CultureInfo("sv-SE")).Substring(0, 2);
                                    <label style="padding-left: 10px">
                                        <input type="checkbox" class="selectedId" name="isoDate" value="@isoDate"/>@day-@isoDate
                                    </label>
                                }
                            </div>
                        </div>
                    </div>
                </div>
            </div>
        }
        else
        {
            <div class="col-md-12">
                <label>
                    <input type="checkbox" class="selectAll" name="all" />
                    Välj alla.
                </label>
                @foreach (var date in group)
                {
                    var isoDate = date.ToString("yyMMdd");
                    var day = date.ToString("ddd", new CultureInfo("sv-SE")).Substring(0, 2);
                    <label style="padding-left: 10px">
                        <input type="checkbox" class="selectedId" name="isoDate" value="@isoDate" />@day-@isoDate
                    </label>
                }
            </div>
        }
    }
}

i'm new to Asp.net MVC.regular expression to allow special characters / and . for "name" property in asp.net MVC

I have a WCF service which uses Windows Authentication to view Service Contract and a specfic method in a service is configured to be accessed only by a specific user UserX.

[PrincipalPermission(SecurityAction.Demand,Name="xxx\\UserA")]

In the client side, I need to access the above service method. If I am using a Web Reference -> I add the following

client = new WebRefLocal.Service1();
client.Credentials = new System.Net.NetworkCredential("UserA", "xxxxxx", "test");

But the above cannot be achieved in WCF Service Reference as Client Credentials are read-only. One best way I can achieve the above is Impersonation https://msdn.microsoft.com/en-us/library/ff649252.aspx.

My question here is

  1. Why ClientCredentials are made readonly in WCF?
  2. How Network Credential work? Will they authenticate the Windows login in client side or server side?
  3. Is there is any way I can achieve the above in WCF aswell without impersonation?

I have a class in aspx.cs

in that i have a function like below

public static String GetMaritalStatus(String maritalStatus)
        {
            if (maritalStatus == null)
                return "";
            String[] maritalStatuses = new String[] { "--", "Single", "Married", "Divorced", "Widowed" };

            return maritalStatuses[int.Parse(maritalStatus)];
        }

When this function is called I am getting

input string was not in a correct format. Error

on the line

String[] maritalStatuses = new String[] { "--", "Single", "Married", "Divorced", "Widowed" };

What can be the reason.

Edited

String marital = GetMaritalStatus(02);

Is there any possibility to use server tags with RegularExpressionValidator e.g

<asp:RegularExpressionValidator runat="server" ValidationExpression="<%# Common_.getValidationExpression(); %>" ControlToValidate="txtPhone" ErrorMessage="Please enter alphanumeric values" /> 

Actually I want to manage all the regular expressions in single class and I also want to use server tags on ASPX pages not in codebehind :)

Thanks.

I recently been asked by my boss to migrate one our company's website to a new machine running on Windows Server 2012.

I never have any experience in deploying websites on a local machine, much less ASP.Net sites. I managed to bind IIS on the website directory and I can browse it on the server machine yet I can't access it from other machines.

Please help.

I'm in trouble about Caching of asp.net ,thanks in advance if somebody helps. I have an asp.net 3.5 web form application,which is using System.Caching to cache some data.And i need to delete and creat some ".rdlc" files in App_Data folder for some reason. Some codes like below:

    public partial class _Default : System.Web.UI.Page
{
    private const string cacheKey = "%cacheKey%";
    protected void Page_Load(object sender, EventArgs e)
    {
        if (Cache[cacheKey] == null)
        {
            InitCache();
        }
    }

    private void InitCache()
    {
        object myData = new object();
        System.Web.Caching.SqlCacheDependency sqlDep = new SqlCacheDependency("myEntry", "myTable");
        CacheItemRemovedCallback onRemove = new CacheItemRemovedCallback(this.RemovedCallback);
        Cache.Insert(cacheKey, myData, sqlDep, System.Web.Caching.Cache.NoAbsoluteExpiration, System.Web.Caching.Cache.NoSlidingExpiration, CacheItemPriority.Normal, onRemove);
    }

    protected void RemovedCallback(string k, object v, CacheItemRemovedReason r)
    {
        InitCache();
        //Do some stuff...
    }
}

The problem is,every time I delete those ".rdlc" file in app_data folder, the RemovedCallback() will be fired,again and again till the StackOverflow exception throws.What i know is if we delete or change files in bin folder will cause recompile and cache will be removed and the RemovedCallback will be called,but why it would be fired again and again? even if i delete file in app_data folder,not bin folder And ,by the way,what exactly happens to iis when file changed in bin folder?

I want to bind a textbox with a field of DB by using JQuery Code, but I don't know what parameter I can use in AutoComplete function

    $(function () {
        var availableTags = [??????];
        $("#txtSearch").autocomplete({
            source: availableTags });
  });

behind code

public partial class MasterProfile : System.Web.UI.MasterPage
{
SqlConnection cnn = new     SqlConnection(ConfigurationManager.AppSettings["dbpath"]);

protected void txtSearch_TextChanged(object sender, EventArgs e)
{
   FindFriends();
}

void FindFriends()
{
    SqlDataReader dr;
    SqlCommand cmd = new SqlCommand();
    cmd.Connection = cnn;
    cmd.CommandText = "Select * From tblUser where UInfo Like @P1 and UID<> @P2 Order by UInfo";
    cmd.Parameters.AddWithValue("@P1", "%" + txtSearch.Text + "%");
    cmd.Parameters.AddWithValue("@P2", Convert.ToInt64(Session["ud"]));
    cnn.Open();

    dr = cmd.ExecuteReader();
    txtSearch.Text = dr["UInfo"].ToString();
    txtSearch.DataBind();
    cnn.Close();
}

}

I have created Class under App_Code folder there i have created method. I need to call that class method using JavaScript from Sample.aspx file.

Class:

namespace ContactBook.App_Code
{
    //The function need to call...
    public class ContactBook_functionalities
    {
        public static bool MyFunction(string email, string contact)
            {
                 //Code...
            }
    }
}

JavaScript:

<script type="text/javascript">
        function callMyFunc(email, contact)
        {
             //var x = MyFunction(string email, string contact);
        }
</script>

[WebMethod] is not working for Class functions.

I have two environments: Dev and QA. Both running Windows Server 2012 R2. I have an MVC 4 site set up as an application under an existing Classic ASP site. (The existing ASP site does not have its own Web.Config file.)

They're configured exactly the same in Dev and QA except for the machine name and IP addresses. They're both running the exact same build.

The HomeController.cs file is very simple:

    public ActionResult Index()
    {
        return View();
    }

The Index.cshtml file is just as simple:

@{
    ViewBag.Title = "Index";
}

<h2>Index</h2>

/Views/_Layout.cshtml:

<!DOCTYPE html>
<html>
<head>
    <meta name="viewport" content="width=device-width" />
    <title>@ViewBag.Title</title>
</head>
<body>
    @RenderBody()
</body>
</html>

/Views/_ViewStart.cshtml:

@{
    Layout = "~/Views/_Layout.cshtml";
}

On the Dev server, when I go to my site: http://dev/MySite/Home/Index/

It properly executes _ViewStart.cshtml and uses the default _Layout.cshtml that was defined:

<!DOCTYPE html>
<html>
<head>
    <meta name="viewport" content="width=device-width" />
    <title>Index</title>
</head>
<body>
<h2>Index</h2>
</body>
</html>

On the QA server, when I go to my site: http://qa/MySite/Home/Index/

It just renders this:

<h2>Index</h2>

I compared the IIS configurations (even exported them as applications to review the settings in XML, they're the exact same save for the computer name). I edited _Layout.cshtml and _ViewStart.cshtml to throw exceptions, but they never get executed.

What makes things stranger is if I try to manually set the Layout in the view by setting Layout = "~/Views/Layout.cshtml"; on the QA server, I get the following error:

The layout page "~/Views/_Layout.cshtml" could not be found at the following path: "~/Views/_Layout.cshtml".

On Dev, I can manually set the layout this way and it works just fine.

If I do @Url.Content("~/Views/_Layout.cshtml") on Dev and QA, I get the following output:

/MySite/Views/_Layout.cshtml 

What could possibly be causing this? We have other MVC 4 sites running as applications on these servers under the same website and they run perfectly fine.