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();
public ActionResult GetCompanyInfo(string CompanyNumber)
{
string CompanyCUI = CompanyNumber;
Uri myUri = new Uri("https://api.openapi.ro/api/companies/" + CompanyCUI + ".json");
WebRequest myWebRequest = WebRequest.Create(myUri);
myWebRequest.Headers.Add("x-api-key", "8P4RP_kwn71Nt8VG7boFmQb_7NsihyQxT_x7JGcGQkvPdXZH2Q");
WebResponse myWebResponse = myWebRequest.GetResponse();
var dataStream = myWebResponse.GetResponseStream();
var reader = new StreamReader(dataStream);
var jsonResultString = reader.ReadToEnd();
var CompanyInfoData = Newtonsoft.Json.JsonConvert.DeserializeObject<CustomerModels>(jsonResultString);
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("Create", cModel);
return Json(CompanyInfoData,JsonRequestBehavior.AllowGet);
}
public ActionResult Index()
{
string CompanyCUI = "22052442";
Uri myUri = new Uri("https://api.openapi.ro/api/companies/" + CompanyCUI + ".json");
WebRequest myWebRequest = WebRequest.Create(myUri);
myWebRequest.Headers.Add("x-api-key", "8P4RP_kwn71Nt8VG7boFmQb_7NsihyQxT_x7JGcGQkvPdXZH2Q");
WebResponse myWebResponse = myWebRequest.GetResponse();
var dataStream = myWebResponse.GetResponseStream();
var reader = new StreamReader(dataStream);
var jsonResultString = reader.ReadToEnd();
var CompanyInfoData = Newtonsoft.Json.JsonConvert.DeserializeObject<CustomerModels>(jsonResultString);
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);
}
public ActionResult Create()
{
return View(cModel);
}
[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 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; }
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: '/Customers/GetCompanyInfo/?CompanyNumber=' + $('#CompanyNumber').val(),
dataType: "html",
contentType: "application/x-www-form-urlencoded; charset=UTF-8",
success: function (data) {
$('#CompanyNumber').html(data.numar_reg_com);
$('#Name').html(data.denumire);
$('#Address').html(data.adresa);
$('#Phone1').html(data.telefon);
},
error: function () {
}
});
}
)
</script>
}
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):
https://dl.dropboxusercontent.com/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.