I'm working on my first from-scratch back end project. Forgive my ignorance.

I have a page that's filled by data returned from an ASP.net API. I'm connecting to the API successfully using SoapClient, but I'm unable to successfully parse the results.

How can I echo Status in the object below?

The returned object is:

stdClass Object(
    [LoginResult] => {
        "Result":{
            "Status":"FAILED",
            "Message":"Access Denied"},
        "SessionToken":""
    }
)

My code is:

$loginResult->Result;

The error I receive is:

Undefined property: stdClass::$Result.

ViewData["ChildPageMetaConent"] = lstPageMetaContentChilds; // from this line i get data from database and set to ViewData .

Example : in ViewData["ChildPageMetaConent"] have list class. You can check in Image. enter image description here

And on Master.cshtml I am accessing ViewData["ChildPageMetaConent"] variable and gointo to write on page but its print on page like a text . enter image description here

And on HTMl its look like this : enter image description here

So I have my angular.js script in my script folder. I added some code to it and I expect the ASP NET bundler to bundle that version and use it.

When I deployed to production, I'm getting an error saying that some properties don't exists. These properties reside in the Angular JS file. The production is using minified code and I copied that code into a text editor and performed a search for my properties and it didn't find them.

I added this:

child.myProperty = "Some property";

So minified should look something like:

c.myProperty="Some Property";

I'm pointing to the correct file because in DEV it works fine. It's just something in the bundling process is using an old file or something.

My bundle is this:

ScriptBundle("~/bundles/angular").Include(
    "~/Scripts/angular.js",
    "~/Scripts/angular-ui-router.js",
    "~/Scripts/angular-resource.js",
    "~/Scripts/angular-local-storage.js");

I have this property set in the web.config:

<compilation debug="true" targetFramework="4.5.1"/>

What is the most likely cause for this error?

I need to send e-mails from site in HTML-format. User choose a template of e-mail, then write text and send it. Please, answer my questions.

  1. What is the best way to keep templates in database? Currently I am keeping the whole html-template in database.
  2. Are there some special classes for this task? Now, I'm only sent e-mails. Can you show me some info?

Thank you.

I have a collection in my user control which returns values for three properties

Public Class MinimumRequirementResult
    Property Level As String
    Property MinimumRequirement As Int32
    Property ActualRequirement As Int32
End Class

on Button Click event

Public Sub btnSubmit_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles pnlSearch.SearchClick
  _minimumDataSource = GetMinimumLevelCollection()
    'GetMinimumLevelCollection() returns the results of the Level, MinimumRequirement and Actualrequirement
 End Sub

Private _minimumDataSource As System.Collections.Generic.List(Of MinimumRequirementResult)
Public Property MinimumDealerDataSource As System.Collections.Generic.List(Of MinimumRequirementResult)
 Get
 Return _minimumDataSource 
 End Get
 Set(value As System.Collections.Generic.List(Of MinimumRequirementResult))
 If (value Is Nothing) Then Throw New ArgumentNullException("value", "A valid System.Collections.Generic.List(Of MinimumRequirementResult) must be specified")
_minimumDataSource = value
End Set
End Property

Level - Level 1, Level 2 Minimum Requirement - 50, 70 Actual Requirement - 70, 90

How to build columns dynamically?

enter image description here

I am trying to fetch pages data in Facebook using c# MVC. Even though I give manage_pages permission (Scope) it does not show any pages when I run my code. Here is where pagelist is showing 0

string Accounts = "/me/accounts";
JSONObject pageData = api.Get(Accounts);
var data = pageData.Dictionary["data"];
List<JSONObject> pageList = data.Array.ToList<JSONObject>();
ViewBag.pageList = pageList;

Below is the Code that I tried

public ActionResult returnfromfb()
    {
        string app_id = "AppID";
        string app_secret = "AppSecret";
        string scope = "manage_pages,publish_stream,status_update,user_about_me,user_hometown,user_location,email,offline_access";

        string code = Request.QueryString["code"];
        if (code == null)
        {
            Response.Redirect(string.Format("https://graph.facebook.com/oauth/authorize?client_id={0}&redirect_uri={1}&scope={2}",
                app_id, Request.Url.AbsoluteUri, scope));

        }

        string AccessToken = "";
        try
        {
            if (code != null)
            {
                string str = string.Format("https://graph.facebook.com/oauth/access_token?client_id={0}&redirect_uri={1}&scope={2}&code={3}&client_secret={4}",
                app_id, Request.Url.AbsoluteUri, scope, Request["code"].ToString(), app_secret);

                HttpWebRequest req = (HttpWebRequest)WebRequest.Create(str);
                req.Method = "POST";
                req.ContentType = "application/x-www-form-urlencoded";
                byte[] Param = Request.BinaryRead(System.Web.HttpContext.Current.Request.ContentLength);
                string strRequest = System.Text.Encoding.ASCII.GetString(Param);

                req.ContentLength = strRequest.Length;

                StreamWriter streamOut = new StreamWriter(req.GetRequestStream(), System.Text.Encoding.ASCII);
                streamOut.Write(strRequest);
                streamOut.Close();
                StreamReader streamIn = new StreamReader(req.GetResponse().GetResponseStream());
                string strResponse = streamIn.ReadToEnd();
                if (strResponse.Contains("&expires"))
                    strResponse = strResponse.Substring(0, strResponse.IndexOf("&expires"));
                AccessToken = strResponse.Replace("access_token=", "");
                streamIn.Close();
            }

            Facebook.FacebookAPI api = new Facebook.FacebookAPI(AccessToken);
            string requestEmail = "/me";
            JSONObject fbemail = api.Get(requestEmail);
            try
            {
                ViewBag.Email = fbemail.Dictionary["email"].String;
            }
            catch (Exception ex)
            {
                //errorLog.setError(ex, "LoginController.SaveFacebookData");
            }

            string Accounts = "/me/accounts";
            JSONObject pageData = api.Get(Accounts);
            var data = pageData.Dictionary["data"];
            List<JSONObject> pageList = data.Array.ToList<JSONObject>();
            ViewBag.pageList = pageList;
            foreach (var page in pageList)
            {

                try
                {
                   var id = page.Dictionary["id"].String;
                    string request = id;
                    JSONObject fbobject = api.Get(request);
                    try
                    {
                        ViewBag.BusinessName = fbobject.Dictionary["name"].String;
                        ViewBag.Address = fbobject.Dictionary["location"].ToDisplayableString();
                        ViewBag.PhoneNumber = fbobject.Dictionary["phone"].String;


                    }
                    catch (Exception ex)
                    {
                        //errorLog.setError(ex, "LoginController.SaveFacebookData");
                    }
                }
                catch (Exception ex)
                {
                    //errorLog.setError(ex, "LoginController.SaveFacebookData");
                }
            }

Problem

I'm trying to upload file using XMLHttpRequest and it seems to work only with small file (such as under 2MO of size). I tried many things so far and came to code shown at the end of the post. But, there is nothing to do; I keep getting the ::ERR_CONNECTION_RESET error. It is not a code issue as under 2MO files are getting unploaded correctly... What am I forgetting? I know this is probably a IIS or web.config issues but I can put my finger on it by googling this problem.

Error given by Chrome

POST WEBSITEANDSERVICEURL/Service/MyService.asmx/UploadFilesWithAJAX net::ERR_CONNECTION_RESET

  • handleFileSelect
  • x.event.dispatch
  • v.handle

Javascript

<script type="text/javascript">
    $(function() {
        $('#<%= files.ClientID %>').change(handleFileSelect);
    });

    function handleFileSelect(e) {
        if (!e.target.files || !window.FileReader) return;

        var fd = new FormData();
        var file = document.getElementById("<%= files.ClientID %>");
        for (var i = 0; i < file.files.length; i++) {
            fd.append('_file', file.files[i]);
        }
        var xhr = new XMLHttpRequest();
        xhr.open('POST', '<%= ResolveURL("~/Services/MyService.asmx/UploadFilesWithAJAX") %>', true);
        xhr.onreadystatechange = function() {
            if (xhr.readyState == 4 && xhr.status == 200) {
                alert(xhr.responseText);
            }
        };
        xhr.upload.addEventListener("progress", updateProgress, false);
        xhr.send(fd);
    }

    function updateProgress(oEvent) {
        if (oEvent.lengthComputable) {
            var percentComplete = oEvent.loaded / oEvent.total;
            $("#progress").text(oEvent.loaded + " ON " + oEvent.total);
        }
    }
</script>

HTML Markup

<asp:FileUpload ID="files" runat="server" multiple="true" />
<br />
<table id="selectedFiles">
</table>
<span id="progress"></span>

MyService.asmx

<ScriptService()> _
<ToolboxItem(False)> _
<WebService(Namespace:="http://tempuri.org/")> _
<WebServiceBinding(ConformsTo:=WsiProfiles.BasicProfile1_1)> _
Public Class AJAXServices : Inherits WebService
    <WebMethod(EnableSession:=True)> _
    <ScriptMethod(ResponseFormat:=ResponseFormat.Xml)> _
    Public Function UploadFilesWithAJAX()
        ' Some code which work fine, I'm sure of it.
    End Function
End Class

Web.config

<!-- [...] -->
<system.web>
    <httpRuntime maxRequestLength="2097151" executionTimeout="180" /><!-- MAXIMUM DURING TESTING -->
    <!-- [...] -->
</system.web>
<!-- [...] -->

I have a service written using servicestack v3.9. I am trying to return a large result set and am getting an 500 internal server error on my client. If I look at the details of the error I see the results are listed in the exception but are truncated after 65536 characters. I know this is a default limit imposed by .net. What I don't know is how to increase it for service stack.

My client isn't connecting to the service using a binding in the web config since it's using service stack. For web api calls this seems like where you would fix this issue be increasing maxReceivedMessageSize in the binding. I am guessing there is some way to increase this limit for service stack too??

I'm using MVC4, .NET 4.5, VS2012, C#, Razor

I need the public IP of client on my website. To clarify, i need the kind of IP that whatismyip shows. I know about querying whatismyip's automation page. But, I need to obtain the IP myself rather than using some other website for it. Following is my present code.

Controller

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using System.Net;
using System.IO;
using System.Web.Routing;
using System.Net.Sockets;
using System.Text;

namespace abc
{
    public class GetIP : Controller
    {
        public ActionResult GetIP()
        {
            ViewBag.ip1 = string.Empty;
            ViewBag.ip2 = string.Empty;
            ViewBag.defaultgateway = string.Empty;
            ViewBag.ip4 = string.Empty;
            ViewBag.dnsServer = string.Empty;
            ViewBag.ip6 = string.Empty;
            ViewBag.server_IPv6_address = string.Empty;

            if (System.Web.HttpContext.Current.Request.ServerVariables["HTTP_CLIENT_IP"] != null)
                ViewBag.ip1 = System.Web.HttpContext.Current.Request.ServerVariables["HTTP_CLIENT_IP"];

            if (System.Web.HttpContext.Current.Request.ServerVariables["HTTP_X_FORWARDED_FOR"] != null)
                ViewBag.ip2 = System.Web.HttpContext.Current.Request.ServerVariables["HTTP_X_FORWARDED_FOR"].ToString();

            if (System.Web.HttpContext.Current.Request.UserHostAddress.Length != 0)
                ViewBag.defaultgateway = System.Web.HttpContext.Current.Request.UserHostAddress;

            if (System.Web.HttpContext.Current.Request.ServerVariables["REMOTE_ADDR"] != null)
                ViewBag.ip4 = System.Web.HttpContext.Current.Request.ServerVariables["REMOTE_ADDR"].ToString();

            if (System.Web.HttpContext.Current.Request.ServerVariables["LOCAL_ADDR"] != null)
                ViewBag.dnsServer = System.Web.HttpContext.Current.Request.ServerVariables["LOCAL_ADDR"].ToString();

            if (System.Web.HttpContext.Current.Request.ServerVariables["HTTP_X_CLUSTER_CLIENT_IP"] != null)
                ViewBag.ip6 = System.Web.HttpContext.Current.Request.ServerVariables["HTTP_X_CLUSTER_CLIENT_IP"].ToString();

            ViewBag.server_IPv6_address = System.Net.Dns.GetHostEntry(System.Net.Dns.GetHostName()).AddressList.GetValue(0).ToString();

            if (Request.ServerVariables["X-Forwarded-For"] != null)
                ViewBag.ip8 = Request.ServerVariables["X-Forwarded-For"];

            return View();
        }
    }
}

View

Your IP address<br />
Ip1 : @ViewBag.ip1<br />
Ip2 : @ViewBag.ip2<br />
Default Gateway : @ViewBag.defaultgateway<br />
Ip4 : @ViewBag.ip4<br />
DNS Server : @ViewBag.dnsServer<br />
IP6 : @ViewBag.ip6<br />
@*Server's IPv6 Address : @ViewBag.server_IPv6_address*@
IP8 : @ViewBag.ip8<br />

When I put this code on the server, and go the the appropriate url, I get the following result.

enter image description here

And when I go to whatismyip, say I get 123.45.67.89 for example. Why is it that whatismyip can find my IP address but my server can't with all the headers that i have checked. I have also read somewhere about System.Net.Sockets class but i don't know if that would help or what. Please help.

I have copied the AWSSDK.dll to my servers bin directory. I also added this to my web.config:

<add assembly="AWSSDK, Version=2.3.12.0, Culture=neutral, PublicKeyToken=9f476d3089b52be3"/>

I am still getting this error:

The type or namespace name 'Amazon' could not be found (are you missing a using directive or an assembly reference?)

I have this at the top of my aspx file <%@ Import Namespace="Amazon" %>

From here

In general, a Controller shouldn't try to do too much. It should contain only the business logic needed for a single view.

I can't understand why it's controller. It must be model. Please,explain.

EDIT:
This is the example from official developer guider:

angular.module('invoice1', [])
.controller('InvoiceController', function() {
  this.qty = 1;
  this.cost = 2;
  this.inCurr = 'EUR';
  this.currencies = ['USD', 'EUR', 'CNY'];
});

<div ng-app="invoice1" ng-controller="InvoiceController as invoice">
  <b>Invoice:</b>
  <div>
    Quantity: <input type="number" min="0" ng-model="invoice.qty" required >
  </div>
  <div>
    Costs: <input type="number" min="0" ng-model="invoice.cost" required >
    <select ng-model="invoice.inCurr">
      <option ng-repeat="c in invoice.currencies">{{c}}</option>
    </select>
  </div>

What I don't understand is that controller = model here. Am I not right?

There are a lot of questions here regarding this topic but still none of the solutions have helped me, maybe a more experienced person can point me what am I missing.

What I want to achieve is perform a post from a web page to a self hoset ASP web API. Consider the following html markup:

<div>
    <p class="title">Add Subject</p>
    <div>
        <label>Name:</label>
        <input type="text" name="name" id="subjectName"/>
    </div>
    <div>
        <form id="addSubjectForm" action="/subjects/addSubject" method="post" enctype="multipart/form-data">
            <label>Filename:</label>
            <input type="file" name="faceFiles" id="faceFile1" />
        </form>
    </div>
    <div>
        <div class="error" id="addSubjectError"></div>
    </div>
    <div>
        <div class="button active" id="addSubject">Add Subject</div>
    </div>
</div>

and jQuery:

$(document).ready(function()
{
    $("#addSubject.active").click(function(event)
    {
        try
        {
            $("#addSubjectError").text("");
            var formData = new FormData($("#addSubjectForm")[0]);
            $.ajax(
            {
                async: true,
                url: "/subjects/addSubject?name=" + encodeURIComponent($("#subjectName").val()),
                type: "POST",
                data:  new FormData($("#addSubjectForm")[0]),
                context: document.body,
                processData: false,
                contentType: false,
                success: function(data)
                {
                    location.reload(true);
                },
                error: function(XMLHttpRequest, textStatus, errorThrown)
                {
                    try
                    {
                        var response = $.parseJSON(XMLHttpRequest.responseText);
                        if (response.Message != null)
                        {
                            $("#addSubjectError").text(response.Message);
                        }
                        else
                        {
                            $("#addSubjectError").text(errorThrown);
                        }
                    }
                    catch(error)
                    {
                        $("#addSubjectError").text(errorThrown);
                    }
                    $("#addSubject").removeClass("inactive").addClass("active");
                }
            });
            $("#addSubject").removeClass("active").addClass("inactive");
            event.preventDefault();
        }
        catch (error)
        {
            $("#addSubjectError").text("Unexpected error (" + error.Message + ")");
        }
    });
});

I have a corresponding controller with an action in the C# API:

public class SubjectsController : ApiController
{
    [HttpPost]
    [ActionName("addSubject")]
    public void GetAddSubject([FromUri] string name, [FromBody]HttpPostedFileBase faceFiles)
    {
    }

    [HttpPost]
    [ActionName("addSubject")]
    public void GetAddSubject([FromUri] string name, [FromBody]IEnumerable<HttpPostedFileBase> faceFiles)
    {
    }
}

However, when the click handler is executed the methods are not called (I added overloads for a single file and multiple files just in case - initially I had only the method with IEnumerable parameter but then I came to the conclusion that maybe a single element did not qualify for that signature and added another to handle a single file upload).

Looking at the network request in Chrome it seems ok to me:

Request URL:http://localhost:8080/subjects/addSubject?name=abc
Request Method:POST
Status Code:500 Internal Server Error
Request Headersview source
Accept:*/*
Accept-Encoding:gzip,deflate,sdch
Accept-Language:en-US,en;q=0.8
Connection:keep-alive
Content-Length:22708
Content-Type:multipart/form-data; boundary=----WebKitFormBoundaryPy7byeAjO7aovvuD
Host:localhost:8080
Origin:http://localhost:8080
Referer:http://localhost:8080/html/subjects
User-Agent:Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/27.0.1453.116 Safari/537.36
X-Requested-With:XMLHttpRequest
Query String Parametersview sourceview URL encoded
name:abc
Request Payload
------WebKitFormBoundaryPy7byeAjO7aovvuD
Content-Disposition: form-data; name="faceFiles"; filename="es_nemaku_zimet.png"
Content-Type: image/png


------WebKitFormBoundaryPy7byeAjO7aovvuD--

However in all possible cases (method only with single file, method with IEnumerable, both) I get exceptions about missing media formatter classes:

No MediaTypeFormatter is available to read an object of type 'HttpPostedFileBase' from content with media type 'multipart/form-data'

and

No MediaTypeFormatter is available to read an object of type 'IEnumerable`1' from content with media type 'multipart/form-data'

I've seen answers (like this) here to similar questions that advise using json as the container for the data, I'll leave that as a last workaround, but at least this MSDN post demonstrates that the multipart/form-data content type should do. Any suggestions on this?

What is the difference between name and attribute attributes in action tag within StrutsConfig.xml ?

I have a project in MVC5 with C# and Razor Engine.

One of my views, is huge, ans has hundreds of lines of code, thus making it hard to manage. On a previous post this community suggested that I should remove logic from my View and use a ViewModel to have that Logic instead.

However, I fail to see how that helps me. My View shows different information depending on who is seeing it:

if ((User.isHelpDesk && Model.MaterialStatusId == MatStatus.A1HelpDeskProductProposal) || (User.isProcurement && Model.MaterialStatusId == MatStatus.A4PurchasingDptValidation))
{
    <!-- Show something here -->
}
else if (User.isHelpDesk || User.isProcurement || User.isDirector || User.isManager)
{
    <!-- Show some other thing here-->
}

Now, my view has dozens of conditions like the one before. How can a view model help me reduce the code of the view, so it does not contain logic in the form of if and foreach blocks?

I am passing a model to a view partial containing a form that is being loaded asynchronously. Everything seems to be coming across as expected EXCEPT for a DateTime proprty, what would cause this to happen?

Javascript function

function loadUpdateEventForm(eventID) {
        getEventDetails(eventID, function(dnnEvent) {
            if(dnnEvent != null) {
                $("#updateEventForm").load(urlEditEventForm, dnnEvent, function () {
                    $("form#updateEventForm").submit(function (event) { submitNewEvent(event); });
                });
                dialog = $("#updateEventForm").dialog({ modal: true, width: '80%', position: { my: 'top', at: 'top+150' } });
                console.log(dnnEvent);
                return;
            }
        });
}

Output from console.log(dnnEvent)

Object {EventID: 2524, EventName: "sample", EventDescription: "sample", EventTimeBegin: "/Date(1418709600000)/", UserID: 1}

C# Action method serving partial view

public ActionResult _EditForm(DNNEventUpdateModel dnnEvent)
{
    return View(dnnEvent);
}

DNNEventUpdateModel

public class DNNEventUpdateModel
{
    [Required]
    public int EventID { get; set; }
    [Required]
    public string EventName { get; set; }
    [Required]
    [DataType(DataType.MultilineText)]
    public string EventDescription { get; set; }
    [Required]
    public DateTime EventTimeBegin { get; set; }
    public int UserID { get; set; }

    public string EventTimeBeginForDisplay
    {
        get
        {
            return this.EventTimeBegin.ToShortDateString();
        }

        set
        {
            this.EventTimeBegin = Convert.ToDateTime(value);
        }
    }
}

Update

Just realized I forgot to post how this is coming across in the controller. Here is what I mean about the date:

screenshot

I'm trying to submit a form with a file in it through a web api. Everytime I try to send it, the ajax call gives me an error saying this:

jqXHR: [object Object]

textStatus: error

errorThrow: Unsupported Media Type

While in the backend I've got my MVC which doesn't give me that error (Unsupported Media Type):

if (!Request.Content.IsMimeMultipartContent()) //gives false
{
    //415
    return Request.CreateResponse(HttpStatusCode.UnsupportedMediaType);
}

Here is my Jquery code:

$(function () {
    $('#btnSubmit').on('click', function (event) {
        if (isValidJobForm()) {
            console.log('the form is valid');
            processSolicit();
            $(this).closest('form').submit();
        }
    });
});

function processSolicit() {
    var $form = $('#frmApplication');
    $.ajax({
        type: "POST",
        url: "http://consulthrtest.eu/api/register/registercandidate",
        contentType: false,
        processData: false,
        data: $form.serialize(),
        success: function (serverResponse) {
            alert('application service called');
            if (serverResponse.d == 'false') {
                console.log('server unable to process');
            } else {
                notification("Uw sollicitatie is ingezonden!");
            }
        },
        error: function (jqXHR, textStatus, errorThrown) {
            console.log("application failed");
            alert('Inzenden solicitatie mislukt! Probeer nogmaals.' + '\njqXHR: ' + jqXHR + '\ntextStatus: ' + textStatus + '\nerrorThrow: ' + errorThrown);
        }
    }).done(function (result) {
        alert(result.d);
        clearForms($form);
    });
}

Here is my MVC code

public async Task<HttpResponseMessage> RegisterCandidate()
    {
        // Check if the request contains multipart/form-data.
        if (!Request.Content.IsMimeMultipartContent())
        {
            //415
            return Request.CreateResponse(HttpStatusCode.UnsupportedMediaType);
        }

        var provider = new MultipartMemoryStreamProvider();

        try
        {
            // Read the form data.
            await Request.Content.ReadAsMultipartAsync(provider);

            int vacancyTranslationId = 0;
            byte[] fileContent = {};
            string fileName = null;
            string motivation = null;
            ContactDto newContact = new ContactDto();

            foreach (var content in provider.Contents)
            {
                if(content.Headers.ContentDisposition.FileName == null)
                {
                    //handle regular input field
                    switch (content.Headers.ContentDisposition.Name.Replace("\"",string.Empty))
                    {
                        case("firstName"):
                        {
                            newContact.FirstName = content.ReadAsStringAsync().Result;
                            break;
                        }
                        case ("lastName"):
                        {
                            newContact.LastName = content.ReadAsStringAsync().Result;
                            break;
                        }
                        case ("email"):
                        {
                            newContact.Email = content.ReadAsStringAsync().Result;
                            break;
                        }
                        case ("phone"):
                        {
                            newContact.PrimaryPhone = content.ReadAsStringAsync().Result;
                            break;
                        }
                        case ("motivation"):
                        {
                            motivation = content.ReadAsStringAsync().Result;
                            break;
                        }
                        case("vacancyTranslationId"):
                        {
                            vacancyTranslationId = int.Parse(content.ReadAsStringAsync().Result);
                            break;
                        }
                    }
                }
                else
                {
                    //handle uploaded file
                    fileContent = content.ReadAsByteArrayAsync().Result;
                    fileName = content.Headers.ContentDisposition.FileName.Replace("\"", string.Empty);
                }
            }

            if (string.IsNullOrEmpty(newContact.FirstName) ||
                string.IsNullOrEmpty(newContact.LastName) ||
                string.IsNullOrEmpty(newContact.Email) ||
                string.IsNullOrEmpty(newContact.PrimaryPhone) ||
                string.IsNullOrEmpty(motivation) ||
                vacancyTranslationId == 0 ||
                fileContent.Length == 0)
            {
                //406
                return Request.CreateResponse(HttpStatusCode.NotAcceptable);
            }

            var result =_registerContactCommandHandler.Execute(new RegisterContactCommand(newContact, fileName, fileContent , vacancyTranslationId, motivation));

            if (result.HasError)
            {
                //409
                return Request.CreateResponse(HttpStatusCode.Conflict);
            }

            //201
            return Request.CreateResponse(HttpStatusCode.Created);
        }
        catch (System.Exception e)
        {
            return Request.CreateErrorResponse(HttpStatusCode.InternalServerError, e);
        }
    }

And here is the HTML Form:

<form runat="server" id="frmApplication" action="http://consulthrtest.allphi.eu/api/register/registercandidate" method="post" name="frmApplication" role="form" enctype="multipart/form-data">
    <div class="row clearfix">
        <asp:HiddenField runat="server" ID="vacancyId" Value="" />
        <input type="hidden" name="vacancyTranslationId" value="7" />
        <div class="col-sm-6 column form-column">
            <label for="firstName" class="sr-only">Voornaam</label>
            <input runat="server" id="firstName" name="firstName" type="text" class="form-control input-lg" placeholder="Voornaam" />
        </div>
        <div class="col-sm-6 column form-column">
            <label for="lastName" class="sr-only">Achternaam</label>
            <input runat="server" id="lastName" name="lastName" class="form-control input-lg" type="text" placeholder="Achternaam" />
        </div>
        <div class="col-md-12 column form-column">
            <label for="email" class="sr-only">Email</label>
            <input runat="server" id="email" name="email" class="form-control input-lg" type="text" placeholder="Email" />
        </div>
        <div class="col-md-12 column form-column">
            <label for="phone" class="sr-only">Telefoon</label>
            <input runat="server" id="phone" name="phone" class="form-control input-lg" type="text" placeholder="Telefoonnummer" />
        </div>
    </div>
    <div class="col-sm-6 column">
        <label for="motivation" class="sr-only">Motivatie</label>
        <textarea runat="server" id="motivation" name="motivation" class="form-control input-lg" rows="7" placeholder="Motivatie"></textarea>
    </div> 
    <span class="input-group-btn">
        <asp:FileUpload runat="server" ID="cv" />
        <input runat="server" type="text" name="cv" id="fileTextField" class="form-control input-lg" placeholder="Selecteer uw CV" readonly="true" />
        <div class="col-sm-6 column">
            <input id="btnSubmit" type="button" value="Solliciteren" class="btn btn-primary btn-lg pull-right" />
        </div>
    </span>
</form>

How can I submit a form on an image click? The form does not get submitted with the code below. Is there a way to do this without jQuery?

Razor

@using (Html.BeginForm("AssignLabels", "Home", FormMethod.Post, new { name = "frm", id = "AssignLabelsForm" }))
{
   <img src="@Url.Content("~/Images/Labels.png") />
}

jQuery

$('img').on("click", function () {
    $(this).submit();
});

Controller

[HttpPost]
public ActionResult AssignLabels()
{
    return View();
}

i need samples and examples for post,delete,put method on MVC web API with Knockout js. i got an error while running Post method in MVC web API.

Here my code for Post Method:

$.ajax({
   url: 'api/product/PostProduct/',
   cache: false,
   type: 'POST',
   contentType: 'application/json; charset=utf-8',
   data: ko.toJSON(Product),
   success: function (data) {
       alert('added');
       self.Products.push(data);
       self.BrandName("");
       self.price("");
       self.GenericName("");
    }
 }).fail(
       function (xhr, textStatus, err) {
           alert('error');
    });

When i run my application i get: "Uncaught TypeError: Cannot read property 'init' of undefined" The alert in the document reasdy function runs, so i know jQuery is loaded at that point. But i don't know why Task is undefined.

This is in a MVC5 application, and running jQuery 1.10.2

Please help, jsFiddle works fine, and JsHint shows no errors.

    var Task = (function () {

    var initialize = function () {
        console.log($);
        bindEvents();
    };
    var postFilter = function () {
        console.log("clicked");
        var postData = {
            UserID: $('#user_select').val,
            TaskTypeID: $('#taskTypeSelect').val,
            TaskStatusID: $('#status_select').val,
            PriorityID: $('#priority_select').val
        };

        $.ajax({
            url: "/Tasks/_AllTaskView",
            data: postData,
            success: function (response) {
                $('#results').html(response);
            }

        });
    };

    var bindEvents = function () {
        $('#submit_filter').on('click', postFilter);
    };

    return
    {
        init : initialize

    };

})();

$(document).ready(function () {
    alert()
    Task.init();
});

It seems like I have a little mistake in my code. But I cant find it.

So, I'm calling an Action in my Controller from my ajax function.

var serviceURL = '/Vm/GetVMInformation';

$.ajax({
    type: "GET",
    url: serviceURL,
    contentType: "application/json; charset=utf-8",
    dataType: "json",
    success: function (result) {
        alert("This Works fine");
        $("#testDiv").html(result); // Display the partial View in this div
    },
    error: function (XMLHttpRequest, textStatus, errorThrown) {
        alert(errorThrown);
    }
});

My Action then returns a partial view and an list object.

public ActionResult GetVMInformation()
{
    List<VmInfo> VMListArray = new List<VmInfo>();
    ... Code ...
    return PartialView("_List", VmList);
}

The Action gets called and the partial View works. I tested it. So the problem is, my ajax function isnt successful. So it throws an error. When I alert the error I just get "Internal Server Error".

Does anyone see my mistake?

Note: My partial view. Not sure if its important

<!--This partial View is just for testing the ajax function-->

@model IsolutionsAzureManager.Models.VmData

<p>@Model.Name[0]</p>

UPDATE:

So I changed the return type of my function (which has now the type JsonResult) to Json

    JavaScriptSerializer jss = new JavaScriptSerializer();

    string output = jss.Serialize(VmList);
    Response.Write(output);
    Response.Flush();
    Response.End();
    return Json("_List", output);

The good news: The ajax call is now successful. The bad news: I still can't display my partial View. The return value (result) is just [object, Object]

    success: function (result) {
        $("#testDiv").html(result);
    },

I would like to display the user manual of the system as pdf in the browser.

The following code works fine in IE9 but not

Chrome - Error duplicate errors received from server

Firefox - Corrupted content error

The MVC 5 code ( I think is adding duplicate headers which IE can handle)

Just wondering is there any way this will work with all browsers?

public FileResult UserManual()
    {
        var FileName = "user-manual.pdf";
        var cd = new ContentDisposition
        {
            Inline = true,
            FileName = FileName
        };
        Response.AddHeader("Content-Disposition", cd.ToString());
        string path = AppDomain.CurrentDomain.BaseDirectory + "App_Data/";
        return File(path + FileName, MediaTypeNames.Application.Pdf, FileName);

    }