将数据从json发送回MVC中的视图

编程入门 行业动态 更新时间:2024-10-28 16:19:44
本文介绍了将数据从json发送回MVC中的视图的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

我有以下情况:我有一个模型客户的控制器。在创建视图中,我有一个用于在DB中添加客户的表单。我成功完成了以下任务:在表单的编辑框中输入某个值后,通过单击一个专用按钮,我在我的控制器中调用一个方法,将editbox的textvalue作为参数传递,简而言之,该方法发出一个web请求。给定web服务器并最终返回包含我的表单所需数据的JSON(例如,我搜索给定的公司注册号码,在JSON中我找到姓名,地址,电子邮件,电话等)。此后,在我的方法中,我将JSON中的信息绑定到我的模型(在此步骤中所有测试都很好,我有我需要的所有数据)。 我现在想要的是将这些数据发送到每个表单元素并在发送/保存表单之前预先填充它们(在最终版本中,还有一些编辑框不包含在从JSON获取的信息中)并且我可以手动写入表格) 总而言之,在CustomersControler中我有三个与此有关的动作:GetCompanyInfo(这从中检索JSON)一个基于视图中表单参数的Web服务器,Create(GET版本)和Create(POST版本)(Visual Studio最后两个scafolded) 我提供相关代码。 CutomersController中的第一个(我在第一次提问后修改):

Hi, I have the following scenario: I have a controller for model "Customers". In "Create" view I have a form for adding customers in DB. I succeed to do the following task: after entering a certain value in an editbox of form, by clicking a dedicated button I invoke a method in my controller passing the textvalue of editbox as parameter and on brief the method make a web-request against a given web-server and finally returns a JSON that contain data that I need for my form (e.g. I search for a given company registration number and in JSON I find name, address, email, phone etc.). Furthermore after this in my method I bind the information within JSON to my model (at this step all is tested and is fine, I have all data that I need). What I want now is to "send" this data to the each form element and to prefill them before sending/saving form (in final version there will be also a number of editboxes that are not covered by info obtained from JSON and that I may manually write in form) So for summarize, in CustomersControler I have three actions that concerns this: GetCompanyInfo (this retrieve a JSON from a web-server based on parameter from form in view), Create (GET version) and Create (POST version) (last two scafolded by Visual Studio) I provide bellow the relevant code. First in CutomersController (I modified after first ask of question):

public class CustomersController : Controller { private InvoiceDBEntities db = new InvoiceDBEntities(); public Customers cModel = new Customers(); //Ask the web for company details public ActionResult GetCompanyInfo(string CompanyNumber) { //call for openapi.ro //pc94 srl: RO5949570 infosystems4u: 22052442 string CompanyCUI = CompanyNumber; // Create a new 'Uri' object with the specified string. Uri myUri = new Uri("api.openapi.ro/api/companies/" + CompanyCUI + ".json"); // Create a new request to the above mentioned URL. WebRequest myWebRequest = WebRequest.Create(myUri); //Add the required header to request myWebRequest.Headers.Add("x-api-key", "8P4RP_kwn71Nt8VG7boFmQb_7NsihyQxT_x7JGcGQkvPdXZH2Q"); // Assign the response object of 'WebRequest' to a 'WebResponse' variable. WebResponse myWebResponse = myWebRequest.GetResponse(); // Read the response into a stream var dataStream = myWebResponse.GetResponseStream(); var reader = new StreamReader(dataStream); var jsonResultString = reader.ReadToEnd(); // Deserialize var CompanyInfoData = Newtonsoft.Json.JsonConvert.DeserializeObject<CustomerModels>(jsonResultString); //Bind to model for feed him (not all properties, just for illustrating) cModel.Phone1 = CompanyInfoData.telefon; cModel.CompanyRegistration = CompanyInfoData.numar_reg_com; cModel.Name = CompanyInfoData.denumire; cModel.CompanyNumber = CompanyInfoData.cif; cModel.Address = CompanyInfoData.adresa; ViewData["Customer"] = cModel; //Create(); //original when asked the question return View("Create", cModel); //modified version return Json(CompanyInfoData,JsonRequestBehavior.AllowGet); } // GET: Customers public ActionResult Index() { //This is only for testing purpose for demonstrate the behavior desired //call for openapi.ro //pc94 srl: RO5949570 infosystems4u: 22052442 string CompanyCUI = "22052442"; // Create a new 'Uri' object with the specified string. Uri myUri = new Uri("api.openapi.ro/api/companies/" + CompanyCUI + ".json"); // Create a new request to the above mentioned URL. WebRequest myWebRequest = WebRequest.Create(myUri); //Add the required header to request myWebRequest.Headers.Add("x-api-key", "8P4RP_kwn71Nt8VG7boFmQb_7NsihyQxT_x7JGcGQkvPdXZH2Q"); // Assign the response object of 'WebRequest' to a 'WebResponse' variable. WebResponse myWebResponse = myWebRequest.GetResponse(); // Read the response into a stream var dataStream = myWebResponse.GetResponseStream(); var reader = new StreamReader(dataStream); var jsonResultString = reader.ReadToEnd(); // Deserialize var CompanyInfoData = Newtonsoft.Json.JsonConvert.DeserializeObject<CustomerModels>(jsonResultString); //Bind to model for feed him // var cModel = new CustomerModels(); cModel.Phone1 = CompanyInfoData.telefon; cModel.CompanyRegistration = CompanyInfoData.numar_reg_com; cModel.Name = CompanyInfoData.denumire; cModel.CompanyNumber = CompanyInfoData.cif; cModel.Address = CompanyInfoData.adresa; ViewData["Customer"] = cModel; return View(cModel); //default behavior of original view //return View(db.Customers.ToList()); } // GET: Customers/Create public ActionResult Create() { return View(cModel); } // POST: Customers/Create // To protect from overposting attacks, please enable the specific properties you want to bind to, for // more details see go.microsoft/fwlink/?LinkId=317598. [HttpPost] [ValidateAntiForgeryToken] public ActionResult Create([Bind(Include = "CustomerID,Name,CompanyNumber,CompanyRegistration,CompanyBank,CompanyIBAN,Address,CP,City,ContactPerson,Phone1,Phone2,Fax,Email,Notes")] Customers customers) { if (ModelState.IsValid) { db.Customers.Add(customers); db.SaveChanges(); return RedirectToAction("Index"); } return View(customers); } protected override void Dispose(bool disposing) { if (disposing) { db.Dispose(); } base.Dispose(disposing); } }

a简要预览模型(不一定相关,可能会改变,但只是在case)

a briefly preview of the model (not necessarily relevant, it may change, but just in case)

public Customers() { this.Invoices = new HashSet<Invoices>(); } public int CustomerID { get; set; } public List<object> tva_la_incasare { get; set; } public string Name { get; set; } public string CompanyNumber { get; set; } public string CompanyRegistration { get; set; } public string CompanyBank { get; set; } public string CompanyIBAN { get; set; } public string Address { get; set; } public string CP { get; set; } public string City { get; set; } public string ContactPerson { get; set; } public string Phone1 { get; set; } public string Phone2 { get; set; } public string Fax { get; set; } public string Email { get; set; } public string Notes { get; set; } public virtual ICollection<Invoices> Invoices { get; set; }

现在在Create.cshtml视图中(剃刀代码和最后使用的脚本)

and now in Create.cshtml view (razor code and at the end script used)

@using ChameleonForms @using ChameleonForms.Component @using ChameleonForms.Enums @using ChameleonForms.Templates @using ChameleonForms.ModelBinders @model DirectInvoice.Models.Customers @{ ViewBag.Title = "Create"; } <h2>Create Customer</h2> <p>Use for test e.g. pc94 srl: RO5949570 or infosystems4u srl: 22052442</p> <div> @using (var f = Html.BeginChameleonForm()) { @Html.AntiForgeryToken() using (var s = f.BeginSection("Add a new customer")) { @s.FieldFor(m => m.CompanyNumber) @*First approach that don't work*@ @*<button type="button" onclick="location.href='@Url.Action("GetCompanyInfo", "Customers", new { id = "Ask" })'" class="btn btn-default">Ask the web!</button>*@ <button id="Ask" type="button" class="btn btn-default">Ask the web!</button> @s.FieldFor(m => m.Name) @s.FieldFor(m => m.CompanyRegistration) @s.FieldFor(m => m.Address) @s.FieldFor(m => m.City) @s.FieldFor(m => m.Phone1).Placeholder("0XX X XXX XXX") } using (var n = f.BeginNavigation()) { @n.Submit("Save the new customer...") } } </div> <div> @Html.ActionLink("Back to List", "Index") </div> @section Scripts { <script type="text/javascript"> $('#Ask').click(function () { var companynumber = $('#CompanyNumber').val(); $.ajax({ type: 'POST', data: { CompanyNumber: companynumber }, //url from the controller's action method e.g. GetCompanyInfo url: '/Customers/GetCompanyInfo/?CompanyNumber=' + $('#CompanyNumber').val(), //dataType: 'json', //contentType: "application/json; charset=utf-8", //Later edit of the code dataType: "html", contentType: "application/x-www-form-urlencoded; charset=UTF-8", success: function (data) { //Here you would update the textboxes, the 'data' //variable contains the html from the partialview //Later edit of the code $('#CompanyNumber').html(data.numar_reg_com); $('#Name').html(data.denumire); $('#Address').html(data.adresa); $('#Phone1').html(data.telefon); }, error: function () { //Manage errors } }); } ) </script> }

希望以上所有有帮助。任何有关如何使用检索到的JSON数据预填充表单元素的提示都将非常受欢迎。 我还添加了一个打印屏幕(对操作流程有一些解释): dl.dropboxusercontent/u/23409498/Printscreens/2016-09-06%20(3).png [ ^ ] 谢谢 我的尝试: javascript的各种变体,也可以在我的GetCompanyInfo中调用Create()(GET版本)方法,也可以通过我得到的第一个建议进行修改。仍然无法正常工作。

Hope that all above helps. Any hint about how to pre fill the form elements with data from the JSON retrieved, will be very appreciated. I add also a print-screen with what I get now (with some little explanations of operational flow): dl.dropboxusercontent/u/23409498/Printscreens/2016-09-06%20(3).png[^] Thank you What I have tried: Various variants of javascript, also to call Create() (GET version) method in my GetCompanyInfo, and also modified by first suggestion that I get. Still don't work.

推荐答案

(' #询问')。点击( function (){ var companynumber = ('#Ask').click(function () { var companynumber =

(' #CompanyNumber')。val (); ('#CompanyNumber').val();

.ajax({ type:' POST ',数据:{ CompanyNumber:companynumber }, // url例如GetCompanyInfo url:' / Customers / GetCompanyInfo /?CompanyNumber =' + .ajax({ type: 'POST', data: { CompanyNumber: companynumber }, //url from the controller's action method e.g. GetCompanyInfo url: '/Customers/GetCompanyInfo/?CompanyNumber=' +

更多推荐

将数据从json发送回MVC中的视图

本文发布于:2023-11-11 11:15:32,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1578274.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:视图   数据   json   MVC

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!