gpt4 book ai didi

javascript - 如何将 javascript 数组传递给 ASP.NET MVC 模型?

转载 作者:行者123 更新时间:2023-11-29 21:49:23 26 4
gpt4 key购买 nike

我想在 ASP.NET MVC 中创建一个字段对象并将其存储到数据库中。该字段应包含用户可以使用 google maps api 选择的坐标。现在,如何将存储在 javascript 数组中的标记坐标传递到模型的列表?

这是我的 Controller :

using System;
using System.Collections.Generic;
using System.Data;
using System.Data.Entity;
using System.Linq;
using System.Net;
using System.Web;
using System.Web.Mvc;
using BL;
using MvcAgrarTest.Models;

namespace MvcAgrarTest.Controllers
{
public class FieldsController : Controller
{
private MvcAgrarContext db = new MvcAgrarContext();

// GET: Fields
public ActionResult Index()
{
var field = db.CreateFieldViewModel.Include(f => f.FieldType);
return View(field.ToList());
}

// GET: Fields/Create
public ActionResult Create()
{
var model = new CreateFieldViewModel();
ViewBag.FieldTypeId = new SelectList(db.FieldType, "FieldTypeId", "Name");
return View(model);
}

// POST: Fields/Create
[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult Create(CreateFieldViewModel model, CreateFieldViewModel field, string[] markers)
{

if (ModelState.IsValid)
{
PostCoordinates(markers);
db.CreateFieldViewModel.Add(field);
db.SaveChanges();
return RedirectToAction("Index");
}

ViewBag.FieldTypeId = new SelectList(db.FieldType, "FieldTypeId", "Name", field.FieldTypeId);
return Json(true);
}
protected override void Dispose(bool disposing)
{
if (disposing)
{
db.Dispose();
}
base.Dispose(disposing);
}


}
}

这里是我使用 Google map 脚本创建 View :

@model MvcAgrarTest.Models.CreateFieldViewModel

@{
ViewBag.Title = "Create";
}

<h2>Feld anlegen</h2>


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

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

<div class="form-group">
@Html.LabelFor(model => model.FieldTypeId, "Feldtyp", htmlAttributes: new { @class = "control-label col-md-2" })
<div class="col-md-10">
@Html.DropDownList("FieldTypeId", null, "--Feldart auswählen--", htmlAttributes: new { @class = "form-control" })
@Html.ValidationMessageFor(model => model.FieldTypeId, "", new { @class = "text-danger" })
</div>
</div>

<div class="form-group">
@Html.LabelFor(model => model.Size, htmlAttributes: new { @class = "control-label col-md-2" })
<div class="col-md-10">
@Html.EditorFor(model => model.Size, new { htmlAttributes = new { @placeholder = "In Hektar", @class = "form-control" } })
@Html.ValidationMessageFor(model => model.Size, "", new { @class = "text-danger" })
</div>
</div>
<div id="google">
<script src="https://maps.googleapis.com/maps/api/js?sensor=false" type="text/javascript"></script>
<script src="http://ajax.microsoft.com/ajax/jquery/jquery-1.3.2.min.js" type="text/javascript"></script>
<script src="http://ajax.microsoft.com/ajax/jquery.validate/1.5.5/jquery.validate.min.js" type="text/javascript"></script>
<script type="text/javascript">

var map;

function initialize() {
var myLatLng = new google.maps.LatLng(50.617109, 8.065738);
var myOptions = {
zoom: 5,
center: myLatLng,
mapTypeId: google.maps.MapTypeId.ROADMAP
};

map = new google.maps.Map(document.getElementById("map_canvas"), myOptions);

// array to store markers that has been drawn
var markers = [];

// event listener draw a marker
google.maps.event.addListener(map, 'click', function (e) {

var marker = new google.maps.Marker();

marker.setPosition(e.latLng);
marker.setMap(map);
marker.setVisible(true);

markers.push(marker);

// draw polygon on marker click
// once user clicks on on of the markers
google.maps.event.addListener(marker, 'click', function (e) {
document.getElementById("label").innerHTML = "";
drawPoints(markers);
label.style.borderStyle = "dotted"
for (i = 0; i < markers.length; ++i) {
document.getElementById("label").innerHTML += markers[i].position;

}

// empty the markers array
markers = [];
});

});

}

function drawPoints(markers) {
var poly = new google.maps.Polygon;

var points = [];

for (var i = 0; i < markers.length; i++) {
points.push(markers[i].getPosition());
}
poly.setMap(map);
poly.setPath(points);
poly.setVisible(true);
}
</script>
<body onload="initialize()">
<div id="map_canvas" style="width: 500px; height: 300px"></div>
</body>
</div>


<div class="form-group">
<div class="col-md-offset-2 col-md-10">
<input type="submit" value="Erstellen" class="btn btn-default" />
</div>
</div>
</div>

}

最后是我的 ViewModel 来创建字段:

public class CreateFieldViewModel
{
[Key]
[Display(Name="ID")]
public int FieldId { get; set; }

[Required]
[Display(Name="Fieldname")]
public string Name { get; set; }

[Required]
[Display(Name="Fieldtype")]
public int FieldTypeId { get; set; }

[Required]
[Range(0.01, int.MaxValue, ErrorMessage = "The Size can´t be 0 or less")]
[Display(Name="Fieldsize")]
public float Size { get; set; }

[Display(Name="Coordinates")]
public List<string> Coordinates { get; set; }

public virtual FieldType FieldType { get; set; }
}

/edit:我现在这样做了,但还是不行

更改了来自 google maps API 的部分:

var passdata = [];
google.maps.event.addListener(marker, "click", function(e){
for (y=0; y<markers.length; ++y){
passdata[y] = markers[y].position
}
drawpoints(markers);
$.ajax({
url: "@Url.Action("Create","Fields")",
typ: "POST",
datatype: "json",
data: JSON.stringify({coordinates: passdata}),
contentType: "application/json; charset=utf-8",
traditional: true,
success: function (data) {
alert(data);
},
});

和 Controller 功能:

// GET: Fields/Create
public ActionResult Create()
{
var model = new CreateFieldViewModel();
ViewBag.FieldTypeId = new SelectList(db.FieldType, "FieldTypeId", "Name");
return View(model);
}

// POST: Fields/Create
[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult Create(CreateFieldViewModel field, string[] coordinates)
{

if (ModelState.IsValid)
{
field.Coordinates = coordinates;
db.CreateFieldViewModel.Add(field);
db.SaveChanges();
return RedirectToAction("Index");
}

ViewBag.FieldTypeId = new SelectList(db.FieldType, "FieldTypeId", "Name", field.FieldTypeId);
return View(field);
}

最佳答案

我明白了,(看你的代码)你想要提交表单,而不是 ajax?

如果是这样,你有两个选择(我知道):

  1. 创建 html 隐藏输入并将其粘贴为标记数组的值序列化 JSON - 但稍后您必须反序列化该值。在此示例中,您需要将模型中的坐标类型更改为字符串。

JavaScript

// some sample coordinates, you need to extract them from markers
var coordinates = ["12,21","213,231"];
var dataToSend = JSON.stringify(coordinates);
$("#coordinatesInput").val(dataToSend);

HTML

<input hidden id="coordinatesInput" name="model.Coordinates" value=""/>
  1. 使用 JavaScript(例如追加函数)动态创建许多带有名称 model.Coordinates[i] 和单个坐标值(使用一些循环)的隐藏 html 输入。

JavaScript

var coordinates = ["231,2132","312,231","231,321"];

var container = $("#container");
//container, where you will be adding inputs, in you example it could be form-horizontal class
coordinates.forEach(function(val, i){
container.append('<input hidden name="model.Coordinates['+i+']" value="'+val+'">');
});

当然,使用 AJAX 是更好的方法,AlexB 的答案也是可行的,但它的机制有点不同。最好只使用 AJAX(而不是表单提交),因为在您的示例中您需要使用两个操作,一个用于 AJAX,一个用于表单提交。

关于javascript - 如何将 javascript 数组传递给 ASP.NET MVC 模型?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29962306/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com