我发布一个包含文件和html数据的表单以及一个获取地理编码的函数,但是控制器只从ajax帖子而不是文件中获取数据, 我认为这与按钮发布的事实有关,但我不确定,
@using (Html.BeginForm("Create", "lecture", FormMethod.Post, new { enctype = "multipart/form-data", id = "RestoForm" }))
{
//values has remove for clear
<div class="form-group">
@Html.LabelFor(f => f.RImage) <i class="glyphicon glyphicon-folder-open"></i>
<input type="file" name="RImage" class="btn btn-default btn-sm btn-google btn-group-justified hvr-shadow " />
</div>
<input type="button" class="btn btn-primary btn-lg" onclick="GetLocation()" value="Finish" />
}
@section scripts
{
<script type="text/javascript">
function GetLocation() {
var geocoder = new window.google.maps.Geocoder();
var Street = document.getElementById('txtAddress').value;
var City = document.getElementById('txtCity').value;
var address = City + Street;
console.log(address);
var labelLat = document.getElementById('Latitude');
var labellong = document.getElementById('longitude');
geocoder.geocode({ 'address': address },
function (results, status) {
if (status == window.google.maps.GeocoderStatus.OK) {
var latitude = results[0].geometry.location.lat();
var longitude = results[0].geometry.location.lng();
console.log("Latitude: " + latitude + "\nLongitude: " + longitude); //Ok.
labelLat.value = latitude; //Ok.
labellong.value = longitude;
$.ajax({
url: 'Create',
type: 'POST',
data: $('#RestoForm').serialize(),
datetype: "html",
success: function (data) {
$('#RestoForm').html(data);
}
});
error: function e(xhr, ajaxOptions, thrownError) {
alert(xhr.status);
alert(thrownError);
}
}
});
};
</script>
控制`
[Authorize, HttpPost, ValidateAntiForgeryToken]
public ActionResult Create(LectureFormViewModel viewModel) // RImage =Null
{`
答案 0 :(得分:1)
您可以使用FormData
使用AJAX将文件发送到操作。
var fm = new FormData();
fm.append("Name", $("#Name").val());
fm.append("RImage", $("#RImage").val());
$.ajax({
url: 'Create',
type: 'POST',
data: fm,
datatype: "html",
contentType: false, // Not to set any content header
processData: false, // Not to process data
success: function (data) {
$('#RestoForm').html(data);
}
});