.NET MVC

402

Solutions

299

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

How do i populate a combobox on a MVC VIEW FROM ELEMENTS FROM SQL SERVER DATATABLE USING VB.NET

Thank you
0
Dear experts,

I have created this code in the model of the MVC. objective is to populate the list of class object  in he model and the pass the populated list to contoller and the to view. this model is called login, i have the controller with the name loginController and the respective view

i don't know how to proceed from here.

I also seek advise  was this the best approach. to solve this.

I want to get data from sqlserver database and i populate it on a view. i dont want to use data entity framework.

Thank you



Imports System.Configuration
Imports System.Data.SqlClient

Public Class login
   
    Public Shared businessobj As New businesscls

    Public Class businesscls
        Public bid As String
        Public businesslst As New List(Of businesscls)
        Public Function hh() As businesscls
            hh = Nothing

            Dim sqlconn As SqlConnection
            Dim sqlcmd As New SqlCommand
            Dim spdr As SqlDataReader
            sqlconn = New SqlConnection( _
              "Server=M-PC\DBS;Initial Catalog=datranDb;Persist Security Info=True;User ID=MyUserID;Password=MyPassword;")
            sqlconn.Open()
            sqlcmd.Connection = sqlconn
            sqlcmd.CommandText = "select * from business"
            spdr = sqlcmd.ExecuteReader
            If spdr.HasRows Then
                Do While spdr.Read
                    businessobj.bid = spdr("bid")
                    businesslst.Add(businessobj)…
0
I'm getting the following error:  The objects “TableName” and “TableName” in the FROM clause have the same exposed names. Use correlation names to distinguish them

should I change my code as this. It look like it fixed the issue but I feel I haven't addressed the real problem. This is the line of code I changed:  "inner join #tempprogram  as  tp with (nolock) on program.progdefid = tp.progdefid";

Before:

    if (!searchCriteria.AllProgramCodes && searchCriteria.SelectedProgramCodes != null && searchCriteria.SelectedProgramCodes.Any())
            {
                baseQuery += Environment.NewLine + ServiceAssistantService.Tools.StringExtensions.GetObjectToTempTable(searchCriteria.SelectedProgramCodes.ToList(), "tempprogram", "progdefid", true);
                commonJoinClause += Environment.NewLine + "inner join #tempprogram with (nolock) on program.progdefid = #tempprogram.progdefid";
            }

Open in new window



After:
    if (!searchCriteria.AllProgramCodes && searchCriteria.SelectedProgramCodes != null && searchCriteria.SelectedProgramCodes.Any())
            {
                baseQuery += Environment.NewLine + ServiceAssistantService.Tools.StringExtensions.GetObjectToTempTable(searchCriteria.SelectedProgramCodes.ToList(), "tempprogram", "progdefid", true);
                commonJoinClause += Environment.NewLine + "inner join #tempprogram  as  tp with (nolock) on program.progdefid = tp.progdefid";
            }

Open in new window

0
I use itextsharp c# to populate value to pdf. The textbox is populated accordingly except the checkbox. And I do not know how to make the checkbox (Checked).

Just FYI. the checkbox export value is "Yes" on PDF document that I use.
0
Assume I have super simple MVC API. Our customer will use html jquery to consume the API.
I want to add one token per customer. for example,


customer A token: asdfasdfasfasfasd
customer B token: 23423423423234dsf


1. If the customer's webpage put above token there to consume my API, it has security concern because I can see the token in view source.
2. What is the simple way to implment API with token? I only have 2 to 5 API so I do not need very complex one.

[System.Web.Http.HttpGet]
        public string Get(string firstname)
	{
return firstname;

}

Open in new window

0
I have the following mvc api and the issue is

when i consume the api like http://localhost:51757/api/Pdf?Respondent_Name_1=ricky&test=me, it works fine.
but
when i consume the api like http://localhost:51757/api/Pdf?Respondent_Name_1=ricky, it alerts The requested resource does not support http method 'GET'.

The only difference is I do not add test parameter value there.

(just FYI, I will have more than 20+ parameters. test is just my example. just to keep it short).


how to fix it?

        [System.Web.Http.HttpGet]
        public string Get(
                
        string Respondent_Name_1, string test 
         
        ) //api/values?id=1
        {
            Domain.DisciplinaryComplaint dd = new Domain.DisciplinaryComplaint();
            MasterController.Service ser = new MasterController.Service();
            dd.respondentName_1= Respondent_Name_1;
            dd.fileExtensionInPDF = ".pdf";
            dd.webpageFileName = "default";
            string returnValue = ser.GetDisciplinaryComplaintDownloadData(dd);
            return returnValue;
        }

Open in new window

0
Hi Experts,
I have the following code. I want to display the  message present in Model.UploadIssueMessages  in <li></li> under "InvaliFileFormat" div.

Thanks in advance.


<div class="validation-summary-errors" style="display:none" id="InvaliFileFormat">
         <ul>
            <li> Invalid file format! Allowed file formats are .ai,.eps,.png,.jpg and .pdf</li>
         </ul>
</div>


@if (Model.UploadIssueMessages != null)
{
    //<li></li> should display the message present in Model.UploadIssueMessages instead of a fixed message
}

Open in new window

0
Hi Experts,
I have this attached page in MVC. I have 3 required fields Business email address, Homepage URL and Description. When I try to submit the form it shows me error because they are required fields. But also have one not required field "Choose file". When a file is selected I am checking for the extension. If the extension is not allowed then I am displaying the msg at the top. But in that case I don't want the form to be submitted either. But right now I can show the error message but don't know how to stop submitting the form.

I am checking for the input file format in the change event.

<script language="javascript" type="text/javascript">
    jQuery(document).ready(function () {
        jQuery("input[type=file]").change(function(e) {
            var fileName = e.target.files[0].name;
            jQuery.ajax({
                type: "POST",
                url: '@Url.Action("CorrectFileFormat", "Login")',
                data: '{PageType: "LOGOSUBMIT", FileName: "' + fileName + '"}',
                contentType: "application/json; charset=utf-8",
                dataType: "json",
                success: function (response) {
                    if (response == false) {
                        var msg = "Invalid file format! Allowed file formats are .ai,.eps,.png,.jpg and .pdf";
                        jQuery('#Wrong_File_Format_msg').html(msg);
                        jQuery("#File_Format_Msg").show();
                    }
                    else {
 

Open in new window

0
I have a radiometric image (320px by 240px) with temperature data behind each pixel

I have extracted the temperature data and put into float[320, 240];
Then I can reference by X Y and get the temperature data


This all works fine, I over lay the temperature data over the image, and when the user hovers it shows the temperature data for that pixel

however I need to now increase the size of the image for display purposes and on hover show the temperatures, the image bit is easy, I just set in CSS

However, the original data (X Y pixels) also needs to be stretched so when the user hovers it shows the correct temperatures
The issue is the original data half the size, so would somehow need to duplicate diagonally

here is the code in question which gets the data into the float array.
I now need to return a float array of 640,480, with the correct pixel temperature data
Any idea how i would stretch the float array and maintain the correct pixel data considering the original is 320x240 and the output needs to be 640x480 ?

_tempData = new float[320, 240];

            using (MemoryStream ms = new MemoryStream(Convert.FromBase64String(tempContents)))
            {
                BinaryReader br = new BinaryReader(ms);
                for (int x = 0; x < 320; x++)
                {
                    for (int y = 0; y < 240; y++)
                    {

                        //write temp value for pixel
                        float pixelTemperature = 

Open in new window

0
I have an MVC C# web application. I am trying to force a user choose from a drop down; in turn that selection is then used as a parameter to in another dropdown. I have a series of these activities. My first drop down does exactly correct, user chooses a selection, the selection is captured and the controller returns the new list and the user is asked to choose from the second list. My problem is that I cant seem to get the third drop down to get the last selection. I can see the controller is returning the data correctly, but I have something not quite right in the code. Maybe I have a variable or something that is keeping previous values. See my code snips below:

       window.onload = function () {
            document.getElementById("add_Date_Worked").setAttribute("readonly", "readonly");
            document.getElementById("add_Client_ID").onchange = function () {
                if (this.selectedIndex !== 0) {
                    document.getElementById("add_Product_ID").removeAttribute("disabled");

                    /* Client ID Drop Down Parameter Selection Start */
                    $.getJSON("../Home/GetFilteredProducts", { id: jQuery("#add_Client_ID").val() },
                        function (data) {
                            var select = $("#add_Product_ID");
                            select.empty();
                            select.append($('<option/>', {
                                value: 0,
                                text: "Select 

Open in new window

1
I have an MVC C# web application and having issues capturing a date input field value. For some reason, even though the user selects a date from the date picker, the value passed to the control is always the same not sure why. Maybe I have an issue with my code. See code and screen shot of the values below.

cshtmel ------------------------------------------------------
<input type="date" name="Date Worked" id="add_Date_Worked" class="form-control" disabled required />

Open in new window



Controller ---------------------------------------------------
 [HttpPost]
        [ActionName("AddTimeInfo")]
        public ActionResult AddTimeInfoPost(TimeInfo timeinfo, string birthdate)
        {
            if (ModelState.IsValid)
            {
                timeinfo.Date_Worked = DateTime.Parse(string.Format("{0:yyyy-MM-dd}", timeinfo.Date_Worked));                
                try
                {
                    timeinfoDao.InsertTimeInfo(timeinfo);
                    TempData["Success"] = "true";
                }
                catch (Exception e)
                {
                    TempData["Success"] = "false";
                }
            }
            else
            {
                var errors2 = ModelState
                    .Where(x => x.Value.Errors.Count > 0)
                    .Select(x => new { x.Key, x.Value.Errors })
                    .ToArray();
                TempData["Success"] = "false";
            }
            return RedirectToAction("TimeInfo", "Home");
        }

Open in new window

1
I have an MVC C# Web Application and need to add some javascript to a partial view. I cannot seem to get the partial view to recognize the javascript. Every time I run the partial view in google dev, I get the error "cannot find the function". How can I include javascript in a partial view?
1
I have an MVC C# Web Application and have a text area input field that needs to be hidden when the page loads. I also have a drop down input field that a user picks a value from the drop down list. What I'm trying to do is if the user selects "Free Text" option with a value of "55" from (add_Time_Description_ID) input, the div area (divTimeNotes) becomes visible. So...this div area will toggle hidden/unhide based on the drop down selection. If page loads and the drop down does not = 55, div is hidden. I'd like to do this with Javascript but am having issues accomplishing. Can someone assist. See input names below:

                <div class="row mg-t-20">
                    <label class="col-sm-5 form-control-label">Time Description:</label>
                    <div class="col-sm-6 mg-t-10 mg-sm-t-0">
                        <select name="Time_Description_ID" id="add_Time_Description_ID" class="form-control" required>
                            <option value="">Select a Time Description</option>
                            @{
                                foreach (TimeDescription timeDescription in Model.TimeDescriptions)
                                {
                                    <option value="@timeDescription.Time_Description_ID">@timeDescription.Time_Name</option>
                                }
                            }
                        </select>
                    </div>
                    <label class="col-sm-1 …
1
I have an MVC C# Web Application. In a modal, I am requesting the user to enter a few fields about their company. Several of the inputs are dropdowns populated by a database. My issue is that the dropdown fields are not required, and the page is not valid unless there is a selected value. How can I make this optional? The specific error that I get regarding the "State" dropdown is: "Key:State_ID Error". If I make a selection in the "State" dropdown, page is valid and data is inserted into the database.


Controller Snippet -------------------
       [HttpGet]
        public ActionResult Client()
        {
            ViewData["Success"] = (string)TempData["Success"] ?? "";
            VM_Client vmClient = new VM_Client
            {
                Clients = clientDao.GetClients()
            };
            GetUserCookies();
            return View("~/Views/Maintenance/Master/Client.cshtml", vmClient);
        }

        [HttpGet]
        public ActionResult AddClient()
        {
            VM_AddClient addClient = new VM_AddClient
            {
                States = stateDao.GetStates(),
                Countries = countryDao.GetCountries(),
                TimeZones = timeZoneDao.GetTimeZones(),
                Industries = industryDao.GetIndustries(),
                CompanyTypes = companyTypeDao.GetCompanyTypes()
            };
            return PartialView("~/Views/Shared/Modals/Client/_AddClientPartial.cshtml", addClient);
        }

 …
0
i have mvc / c# /razor app that have been using for many years.
Now I want to have a page that can keep scroll position. e,g, i have razor webpage and inside have 5 to 8 buttons, and each each usually do some post back with jquery call.

I just want something super simple so I can implement the feature. Thanks

See below has some sample but I do not know how to implement them.

https://stackoverflow.com/questions/11653152/mvc-razor-outputting-text-in-position-to-the-screen/11653295
0
Hello,
I am trying to build an app in ASP.NET MVC amd get this error:
Server Error in '/' Application.
The resource cannot be found.
Description: HTTP 404. The resource you are looking for (or one of its dependencies) could have been removed, had its name changed, or is temporarily unavailable.  Please review the following URL and make sure that it is spelled correctly. 

Requested URL: /Views/Random.cshtml

Open in new window


Any suggestions?

Thanks
0
we are looking for 800 phone no with api. meaning when someone call 800 phone no. we want api to be called immedately to www.myweb.com/phone no
then redirect to 310.222.2222

do you know which provider can. do it? just like something out of the box without too much coding involved
0
Hi All,
Advance thanks!
Have jqgrid and need hyper link on one of the column. Click the link , show new popup window. Closing the window , refresh the parent screen.

Kind regards,
Pooja
0
I am using MVC 5 with entity framework version 6 and a SQL server database. I used the database first model to generate the model, controllers, and views.

I have a database with existing data. It has a list of customers and related meetings. One table contains the customers and the other table contains the meetings. One customer can have multiple meetings but a meeting is only associated with a single customer.

I want a link on the Customer details page to create a new meeting based on the ID of the customer in the details view.
 

Here is the code for the customer details view.
@model CRM.Models.Customer

@{
    ViewBag.Title = "Details";
}

<h2>Details</h2>

<div id="CustomerDetails">
    <h4>Customer</h4>
    <hr />
    <dl class="dl-horizontal">
        <dt>
            @Html.DisplayNameFor(model => model.SystemOfRecordId)
        </dt>

        <dd>
            @Html.DisplayFor(model => model.SystemOfRecordId)
        </dd>
        <br />
        @*<dt>
                @Html.DisplayNameFor(model => model.Relationship)
            </dt>

            <dd>
                @Html.DisplayFor(model => model.Relationship)
            </dd>*@

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

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

        <dd>
            @Html.DisplayFor(model => model.Name)
        

Open in new window

0
Hi Experts,
I have a text box with ID CustomerEmailAddress and on blur it validates the email and display a warning message at the top. If there is a warning message I want to change the corder color of the text box to red. I added some code(In bold). But still it is not working.  Any suggestions?
 jQuery(document).ready(function () {
        jQuery("#CustomerEmailAddress").blur(function () {
            jQuery.ajax({
                type: "POST",
                url: '@Url.Action("BusinessDomain", "Marketing")',
                data: '{email: "' + jQuery("#CustomerEmailAddress").val() + '" }',
                contentType: "application/json; charset=utf-8",
                dataType: "json",
                success: function (response) {
                    if (response == true) {
                        var CustomerEmailAddress = jQuery("#CustomerEmailAddress").val();
                        CustomerEmailAddress = jQuery.trim(CustomerEmailAddress);
                        var DomainName = CustomerEmailAddress.split("@@")[1];
                        var msg1= "Please provide an email address that has a business domain. Email domains at ";
                        var msg2 = " require further review by the program and will cause a delay in your application being approved.";
                        var msg = msg1 + DomainName + msg2;
                        jQuery("div.validation-summary-warning", "#frmSubmitCustomerInformation").text(msg).show();
                       

Open in new window

0
Hi Experts,
I have this to display a message dynamically onblur event of a textbox.
jQuery("#formEnroll").prepend("<div class='validation-summary-warning'>" + msg + "</div>") 

Open in new window


But it keeps adding the div every time when the focus is lost. So how can I check and display  the div only once. only if the div is not exists. It is really urgent!

Thanks in advance.
0
I have this code which calls a controller method from a hompeage.aspx

<a href="Home/Get"><input type="button" value="Click Me" /></a>

Open in new window


How do I pass a parameter to the controller method?
0
Within the actionresult below, i want to redirect to www.google.com.
I tried a few options but still not working...can you help?

 public ActionResult Upload()
        {
             bool isSavedSuccessfully = true;
            string fName = "";
            string fleetID = Request.Url.Segments.Last();
            string returnFleetID = string.Empty;             
            try
            {
                foreach (string fileName in Request.Files)
                {
                    HttpPostedFileBase file = Request.Files[fileName];
                    //Save file content goes here
                    fName = file.FileName;
                    if (file != null && file.ContentLength > 0)
                    {
                        var originalDirectory = new DirectoryInfo(string.Format("{0}Images\\Fleet", Server.MapPath(@"\")));
                        string pathString = System.IO.Path.Combine(originalDirectory.ToString(), "imagepath");//fleetID
                        var fileName1 = Path.GetFileName(file.FileName);
                        bool isExists = System.IO.Directory.Exists(pathString);
                        if (!isExists)                             
                            System.IO.Directory.CreateDirectory(pathString);
                            var path = string.Format("{0}\\{1}", pathString, file.FileName);
                            file.SaveAs(path);
                            returnFleetID = UpdateFleetImage(fleetID,fileName1);
    

Open in new window

0
Hi all

I would like to remotely connect to ms-sql database through port 1433 connection. which service provider/hosting service provider for ASP.NET that can help me get this.

I am having a desktop application. I would want this application to remotely write data to a website database.  

Regards

Anthony
0
https://open.esignforms.com

one of my developers suggest to use this esign api for our company we are heatlh insurance broker in FL.

we all know docsign and they are just so expensive to us
and we don't compare this esign form with docsign.

just want to hear all experts what you think about this product from security, performance, and development sides
0

.NET MVC

402

Solutions

299

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
>