.NET MVC

399

Solutions

298

Contributors

Microsoft’s ASP.NET MVC is a web application framework that implements the model–view–controller (MVC) pattern. As an open-source software, it’s set apart from the ASP.NET Web Forms component, which is proprietary.

Share tech news, updates, or what's on your mind.

Sign up to Post

Hi Experts,

I have this dropdown list. For example it has 4 values , "A, B, C, D"
 @Html.FacetDropDownListWithDefaultFor(m => m.SecretQuestionId, Model.SecretQuestionSelectList, new { @class = "special-dropdown", title = HttpUtility.HtmlDecode(T("Please specify").Text), unselectedvalue = 0 })

Open in new window


I want to pass those 4 to the controller in a hidden field. So I created

@for (int i = 0; i < Model.SecretQuestionSelectList.Count; i++)
{
    @Html.HiddenFor(m => m.SecretQuestionSelectList[i])
}

Open in new window


When I go to the controller, I have 4 items in "SecretQuestionSelectList" but they all are "null".  I want those 4 values "A, B, C, D" to pass to the controller.

Thanks in advance!
0
Hi Experts,

I have a string defined as
public string SecretQuestion{
            get {
                if (SecretQuestionId > 0 && SecretQuestions != null && SecretQuestions.Any()) {
                    return (from s in SecretQuestions where s.SecretQuestionId == SecretQuestionId select s.Value).FirstOrDefault();
                }
                return null;
            }
		}

Open in new window


Right now this string has only get property. How can I add the set property so that I can write value to it.

Thanks in advance!
0
Hi Experts,

I have the following code.
<div>
    <a  href="\join?lang=fr-CA" id="btnReset">@T("Reset")</a>
    <a  id="btnApply">@T("Apply")</a>
</div>

Open in new window


Is it possible to make this href dynamic? An input hidden field "CultureLanguage"  contains the language. If it is "En" then I want the URL to be "\join?lang=EN". Otherwise \join?lang=fr-CA.
I am using C# and MVC

Thanks in advance.
0
I have the following code block in my razor page that I'm trying to prevent special character. How would I use the Html.Raw syntax in the following code block for the label bellow:

       @xxxt.Tools.Language.Translate(xxx.Tools.Language.Keys.Address_Search, ViewBag):

Open in new window

0
I use fullcalendar plugin with mvc.
I knew my MVC API is working and return data. But I do not see the return data on the calendar.
What did i do wrong in Event Push in Jquery?


<script>
        function Can() {
            $('#calendar').fullCalendar({
                header:
                {
                        left: 'prev,next today',
                        center: 'title',
                        right: 'month,basicWeek,basicDay'
                    },
                buttonText: {
                    today: 'today',
                    month: 'month',
                    week: 'week',
                    day: 'day'
                },
                views: {
                    basicWeek: {
                        type: 'basic',
                        duration: { months: 3 },
                        rows: 8
                    }
                },
                events: function (start, end, timezone, callback) {
                    $.ajax({
                        url: '/Park/bookinglist',
                        type: "Post",
                        dataType: "JSON",
                        success: function (result) {
                         var events = [];
                         $.each(result, function (i, data) {
                             //alert(data.ParkProductInventoryCustomNo);
                               events.push(
                               {
                                   title: "test",
                                 

Open in new window

0
I am using ASP.NET MVC 5 with entity framework. I have an existing SQL database that houses a table with a path and name for an attachment (Attachment) that links to another table (Meeting). I want the details view of the Meeting to show the name of the attachment and a link to download the attachment. The attachments are stored on a server on the same network. The attachments are not housed in SQL. I will also want to update the create view to create an attachment but I want to tackle one thing at a time.

Sidenote: This project was created using Entity Framework scaffolding so most of the code is default created from the scaffolding.

Meeting Details View

@model CRM.Models.Meeting

@{
    ViewBag.Title = "Details";
}

<h2>Details</h2>

<div id="MeetingDetails">
    <h4>Meeting</h4>
    <hr />
    <dl class="dl-horizontal">
        <dt>
            @Html.DisplayNameFor(model => model.InteractionDate)
        </dt>

        <dd>
            @Html.DisplayFor(model => model.InteractionDate)
        </dd>
        <br />
        <dt>
            @Html.DisplayNameFor(model => model.Notes)
        </dt>

        <dd>
            @Html.DisplayFor(model => model.Notes)
        </dd>
        <p />

        <dt>
            @Html.DisplayNameFor(model => model.CustomerCallDecisionedBy)
        </dt>

        <dd>
            @Html.DisplayFor(model => model.CustomerCallDecisionedBy)
        </dd>
        <br />
        <dt>
            @Html.DisplayNameFor(model => 

Open in new window

0
Hello,
I am using Jquery Datatable like below. But on link click,not sure why the tab here is opening twice and also on left side of original page(rather then right)and also the original page is refreshing. Any suggestions please to fix this.

var table=$('#example').DataTable( {
destroy: true,

    columns: [
        { data: 'StudentId',title:'StudentId',render: function (data, type, row) {
         
                if(type === 'display'){
                   data = '<a   id= "testlink"  target="_blank"   href="#"  >' + data + '</a>';
               }
               return data;
            }
        }      
    ]
} );
===================================================================
$('#example tbody').on( 'click', 'tr', function () {

  
   $.ajax({
            
            url:"http://localhost/student/class/URLInfo?studentId="+ studentId,            
            error: function(data) {
               var test=""; 
            },
            success: function(data) {
              var test="";          
             // window.open(data);
             window.location.href=data;
             
            
              //window.location.href=data;
        
            }
            
        });     
} );

Open in new window

0
Following on from this question
https://www.experts-exchange.com/questions/29143196/Float-array-in-c-when-passed-to-JS-it's-in-wrong-order.html?headerLink=workspace_answered_questions

I now need to
call the following

 $.ajax({
                type: "POST",
                url: "@Url.Action("CameraChange", "Home")",
                contentType: "application/json; charset=utf-8",
                dataType: "json",
                success: function (response) {
                   imageDataArray = response.DataArray;
                }

Open in new window



However I've no idea how to convert to returned string
[[273.7,273.8,273.8,274.6,274.6,274,274,274.3,274........ ]]

Open in new window


to the JS object: imageDataArray

In the othe question i used @HTML.RAW, which works great and i can then access the data like
imageDataArray[x][y]

Open in new window

to get the value at that position

How would i do this in Js/Jquery?
0
Anyone please suggest , how to achieve this.

I am using Jquery-Ajax with URL below :

 url: "http://localhost/student/class/attendance?dateFrom=636869952000000000&dateTo=636912287999990000&categoryId=1",


I want to pass these 3 parameter information (dateFrom,dateTo,categoryId) into  REST WEB API controller method as below :


        [Route("student/class/attendence")]
        [HttpGet]
        public HttpResponseMessage GetStudentInfo(string dateFrom, string dateTo,string categoryId)
        {


        }


Can anyone suggest option to achieve this please?

Thanks.
0
I have directory website that have many owner and some items  will be listing on the website for sale.

I work as middle name to get commission and I hope to
have a billing service for each owner.

what is the best approach? and what credit card service works in this situation?
0
I am using ASP.NET with an MVC 5 project and entity framework. I want to remove the required attribute that is created implicitly based on the SQL database field. I keep getting entity validation errors on the EMailAddress2 field in the form. I tried these two things among others.

1)  I added @{ Html.EnableClientValidation(false);} to the code in the create view for that div, but that did not resolve the issue.
2) I added DataAnnotationsModelValidatorProvider.AddImplicitRequiredAttributeForValueTypes = false; to the global.asax.

Create view code:

<h2>Create</h2>

@{ Html.EnableClientValidation(false);}
@using (Html.BeginForm())
{
    @Html.AntiForgeryToken()

    <div class="form-horizontal">
        <h4>user</h4>
        <hr />
        @Html.ValidationSummary(true, "", new { @class = "text-danger" })
        <div class="form-group">
            @Html.LabelFor(model => model.CustomerName, htmlAttributes: new { @class = "control-label col-md-2" })
            <div class="col-md-10">
                @Html.EditorFor(model => model.CustomerName, new { htmlAttributes = new { @class = "form-control" } })
                @Html.ValidationMessageFor(model => model.CustomerName, "", new { @class = "text-danger" })
            </div>
        </div>

        <div class="form-group">
            @Html.LabelFor(model => model.AccountNumber, htmlAttributes: new { @class = "control-label col-md-2" })
            <div class="col-md-10">
                @Html.EditorFor(model 

Open in new window

0
i have 10000+ images and I want to prevent people download the images. I am thinking using watermark (my domain name). and my question is below.

1. using c# and mvc / razor, is it possible to add watermark on the image? like a domain name from left top to right bottom.
2. if the watermark text is added, will it still show on the image if someone downloaded it?

3. do you have any ideas beside the watermark?
0
Hi, I have the float array which is populated in c#

temperatureData= new float[570, 429];

Open in new window



I then prepare the data in c# to be send to the front end by doing the following (this might be where its going wrong)

System.Web.Script.Serialization.JavaScriptSerializer jSearializer = new System.Web.Script.Serialization.JavaScriptSerializer();
jSearializer.MaxJsonLength = int.MaxValue;
pd.TemperatureDataArray = jSearializer.Serialize(temperatureData);

ViewBag.TempDataArray = pd.TemperatureDataArray;

Open in new window



then in the front end i have

var tempDataArray = @(ViewBag.TempDataArray);


var imageTemperatureDataArray = JSON.stringify(tempDataArray);
imageTemperatureDataArray = JSON.parse(imageTemperatureDataArray);


alert(imageTemperatureDataArray[321, 228]);

Open in new window


However the value in position 321,228 in JS is not the same as in C#, so i assume its re-ordered the data some how


Can anyone advise where its getting muddled up?


I've attached the dataset which is was taken on a BP on this line
ViewBag.TempDataArray = pd.TemperatureDataArray


The correct value in the float array at this position  [321, 228] should be 346.795624
However in the front end i'm seeing 304.92453
0
I'm very new to MVC5 using razor. I've been able to stumble through some problems but I'm stuck now. Here's what I need to do:

  • Move items from one listbox control to another listbox control
  • Access/get the items from both list boxes at some point in time for processing

my model contains the following:

        public IEnumerable<SelectListItem> AllAvailableServices { get; set; }

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

		public IEnumerable<SelectListItem> AddedServices { get; set; }

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

Open in new window


my view contains the following. I would like to access the items in the AddedServices list when the user clicks the "Submit" button

@using (Html.BeginForm("Category", "Manager", FormMethod.Post))
{
    <table class="contain">
        <tr>
            <td>
                <table class="nav">
                    <tr class="nav">
                        <td class="navLeft">
                            <input type="submit" value="Submit" name="btnSaveCategory" class="button" onclick="location.href = '@Url.Action("UpdateCategoryAndServices")'"/>
                            <input type="button" value="Back" name="btnBack" class="button" onclick="location.href = '@Url.Action("Back")'"/>
                        </td>
                    </tr>
                </table>
            </td>
        </tr>
.
.
.
            

Open in new window

0
I used open source Packet Capture(Pcap) and Wireshark to view video sent by USB Device.  The device sends 512 Bytes packet about every 200 us.  It's a composite device class.  It's a virtual port and bulk video.  Each monochrome raw frame is 640 x 480.

There is a GUI tool that runs in windows that extracts video from this USB device and plays video on the PC.  The company who wrote this GUI tool gave us the source code.  I opened this source code into Visual Studio 2017 Professional version without creating a solution or project.  There are Sixteen projects in this codebase.

The code is in C Sharp.  How do I find out if this codebase will build?  I didn't see any makefiles in this codebase.  Do I need to make any changes to build it?  Do I build project at a time?  How to find out if it's complete solution or just libraries?
0
Hello Experts,

What is the difference between Tasks vs Threads.
0
I am trying to use Data Annotations and regex to validate an address field in a .net MVC application (to disallow the word 'suite' in any form).

I have the following definition in my annotations class:
 
    [MetadataType(typeof(LocationMetaData))]
    public partial class Location
    {

    }

    public class LocationMetaData
    {
        [RegularExpression(@"^(?:(?!\bsuite\b).)*$/ig", ErrorMessage = "Invalid Street1 format - Enter suite information in Street2")]
        public String street1 { get; set; }
    }

Open in new window


...which should only match when the string does not contain 'suite'.

I am getting the failed error message no matter what I enter in the field.

I have tried these variations on the Regex:
^((?!suite).)*$/ig
/^((?!suite).)*$/ig
/^((?!\b(\w*suite\w*)\b).)*$/ig

These all work in online regex testers, but fail in my app.

Does anyone have a working solution for this?

Thanks.
0
Below is mvc api - very classic json return API.
I use datatable js to show the data.
But below javascript shown nothing. The error part shows empty as well. but when I browse api on url. I can see the json format result.
any one knows what is wrong?

        
        [System.Web.Http.HttpGet]
        public List<Domain.Accounting.Report> Get(int id)
        {
            #region call service - master
            Domain.Accounting.Report rr = new Domain.Accounting.Report();
            MasterController.ServiceAccounting ser = new MasterController.ServiceAccounting();
            #endregion
            #region collect optional data 
            rr.invoicestartdate = 20181201;           
            #endregion
            #region call method and return value
            List<Domain.Accounting.Report> returnList = ser.Aging(rr);
            return returnList;
            #endregion 
        }


<script type="text/javascript">
    $(document).ready(function () {
        $.ajax({
            url: 'http://www.abc.com/api/Accounting/1?Type=json',
            method: "POST",
            contentType: "application/json; charset=utf-8",
            dataType: "json",
            success: function (data) {
                var d = JSON.parse(data);
                $('#data-table').dataTable({
                    data: d,
                    paging: true,
                    sort: true,
                    searching: true,
                    scrollY: 200,
                    

Open in new window

0
I have simple mvc Ajax call using JavaScript. and after the call is successfully completed the job. how can I get the data from the server side without refresh?

the Ajax call is to update some records only.

another question is how to keep the vertical position after the call. for example, some of the webpage will have to scroll down to see information and I want to keep scroll down position.
0
Hello,

I am using .net, 4.6.1 MVC web application to have the user login into external authentication (Office 365 for now). I am able to sign-in but unable to set the claims and my Request.IsAuthenticated is always false.

Unable to hit this code.
Provider = new MicrosoftAccountAuthenticationProvider
                {
                    OnAuthenticated = async context =>
                    {
..
..
}

Open in new window


Please advice.

Thanks.
AccountController.txt
Startup.txt
Login.txt
0
I want to use the Chartjs Library to create charts and am starting out with a simple Pie Chart. https://www.chartjs.org/docs/latest/charts/doughnut.html

First of all, I have the Chart.css and Chart.js files copied over to my Scripts folder.
My Controller has the following:

public ActionResult Dashboard()
        {
            int thirtyDays = DB.vw_Expires30Days.Count();
            int sixtyDays = DB.vw_Expires60Days.Count();
            int ninetyDays = DB.vw_Expires90Days.Count();

            double totalCount = Convert.ToDouble(thirtyDays) + Convert.ToDouble(sixtyDays) + Convert.ToDouble(ninetyDays);

            double thirtyDayPercentage = Math.Round((thirtyDays / totalCount) * 100, 2);
            double sixtyDayPercentage = Math.Round((sixtyDays / totalCount) * 100, 2);
            double ninetyDayPercentage = Math.Round((ninetyDays / totalCount) * 100, 2);

            List<PieSeriesData> pieData = new List<PieSeriesData>();

            pieData.Add(new PieSeriesData { Name = "30 Days", Y = thirtyDayPercentage });
            pieData.Add(new PieSeriesData { Name = "60 Days", Y = sixtyDayPercentage });
            pieData.Add(new PieSeriesData { Name = "90 Days", Y = ninetyDayPercentage, Sliced = true, Selected = true });

            ViewData["pieData"] = pieData;

            return View();
        }

Open in new window


My Dashboard View has the following:

@Scripts.Render("~/Scripts/Chartjs/Chart.js")

<script>
var ctx = document.getElementById('myChart');
var myChart = new Chart(ctx, {
    type: 'pie',
    data: {
        labels: ['30 Days', '31-60 Days', '61-90 Days'],
        datasets: [{
            label: 'Warranty Expiration',
            data: @ViewData["pieData"] as List<PieSeriesData>,
            backgroundColor: [
                'rgba(255, 99, 132, 0.2)',
                'rgba(54, 162, 235, 0.2)',
                'rgba(255, 206, 86, 0.2)'
            ],
            borderColor: [
                'rgba(255, 99, 132, 1)',
                'rgba(54, 162, 235, 1)',
                'rgba(255, 206, 86, 1)'
            ],
            borderWidth: 1
        }]
    },
    options: {

    }
});
</script>

<div class="container">
    <div class="col-xs-12">
    <div class="row">
        <div class="col-xs-10 col-xs-offset-1">

            <canvas id="myChart" width="400" height="400"></canvas>

        </div>

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

Open in new window

The chart does not render.  I'm trying to figure out what's missing.
0
I have the following class in a file called classfleet.cs

public class Fleet
{
        
        public string Make { get; set; }
        public string Model { get; set; }
}

Open in new window


on the aspx webpage, I want to get like below.

<asp:textbox text="Make" />
<asp:textbox text="Model" />

All I want is to get the class child name. not the value.
Is it possible with c#? Please show me how if it is possible.
0
I have the following code that returns one record. I need to convert this to a list and return single or more than one.

public string GetApproverEmail()
        {
            try
            {

                var user =  (from x in DB.tbl_User
                        where x.Approver == true
                        select x).Single();

                var email = (from x in DB.tbl_GlobalUser
                                  where x.ID == user.UserID
                                  select x.Email).Single();

                return (email);

            }

            catch
            {
                return null;
            }
        }

Open in new window


This sends the email:

public static void Approve(tbl_ChangeRequest cr)
        {
            User user = new User();
            Email mail = new Email("Approval");
            string Email = user.GetApproverEmail();

            string body = ("This is an automated email.<br />" + "" +
                "text here"" +
                 " is ready for approval. <br />" + "<br />" +
             );

            mail.SetBody(body, true);
            mail.AddTo(Email);
            mail.AddCC("");

            mail.Send();
        }

Open in new window

0
i use mailchimp to send email. usually just upload the csv list to mailchimp. nowday, my website is growing and some user changes email address. but i do not know how to keep track. so sometime, i uploaded the csv list with different email address. and when i upload to mailchimp, and sent. it ends up sending two emails.

In this case, how should i handle it?
0
i have subscription website that I want to auto debt our customer e.g. $5.00 per month and make the charge on every 1th of the month.
can paypal or other provider can do it? if yes, can you please show me their api how it works in c#? thanks
0

.NET MVC

399

Solutions

298

Contributors

Microsoft’s ASP.NET MVC is a web application framework that implements the model–view–controller (MVC) pattern. As an open-source software, it’s set apart from the ASP.NET Web Forms component, which is proprietary.

Top Experts In
.NET MVC
<
Monthly
>