简体   繁体   English

ASP.NET MVC4:在更改文本时,执行ajax请求,然后返回json结果并更新模型,而无需重新加载页面

[英]ASP.NET MVC4: On text changed, do ajax request, then return json result and update model without reloading page

I apologize if this is a bit long, but this is my first post and I know I can be put-off by posts with little information, so here it goes. 如果这有点长,我深表歉意,但这是我的第一篇文章,我知道我可能会被很少信息的文章所拖延,所以就到此为止。

I am currently coding in ASP.NET MVC 4 in a view with a strongly typed ViewModel. 我目前在具有强类型ViewModel的视图中使用ASP.NET MVC 4进行编码。 The ViewModel is simple, consisting of primitive datatypes. ViewModel很简单,由原始数据类型组成。 The model is never used to insert or update data in a database, and is only used for one page. 该模型从不用于在数据库中插入或更新数据,仅用于一页。 When the submit button is clicked, I use the controller to perform a variety of queries on a database to see if certain fields are valid (conditions that can't be handled by data annotations), and if there are no invalid fields, I send the data to the next step in my process. 单击提交按钮后,我使用控制器对数据库执行各种查询,以查看某些字段是否有效(数据注释无法处理的条件),如果没有无效字段,则发送数据进入我的流程的下一步。

My situation is this. 我的情况是这样。 Without refreshing the page, I need to: 在不刷新页面的情况下,我需要:

  1. Check to see if the ContactID has changed 检查ContactID是否已更改
  2. If the ContactID has changed and is populated, check the Contact table in the database to see if the ContactID exists 如果ContactID已更改并已填充,请检查数据库中的Contact表以查看ContactID是否存在
  3. If the ContactID exists in the Database, display the Contact's information in the respective textboxes in the model and disable these textboxes 如果数据库中存在ContactID,请在模型的相应文本框中显示联系人的信息,并禁用这些文本框
  4. If the ContactID does not exist, display a model error or some kind of notification (I would prefer not to do an alert, but I'm not picky) in the validation message for the ContactID and set each textbox in the model to null 如果ContactID不存在,请在ContactID的验证消息中显示模型错误或某种通知(我希望不发出警报,但我不挑剔),并将模型中的每个文本框设置为null

The criteria is mainly for the user. 该标准主要针对用户。 The user needs to see what contact is going to be submitted. 用户需要查看将要提交的联系人。 I cannot do a list view because the user still needs to be able to enter contact information if they choose not to enter a ContactID. 我无法执行列表视图,因为如果用户选择不输入ContactID,则仍然需要输入联系信息。 That being said, I will still validate when the user clicks submit just in case. 话虽如此,我仍然会验证用户单击提交时的情况,以防万一。

View 视图

@model ViewModels.OrderViewModel

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

<table>
  <tr>
       <td>
           @Html.TextBoxFor(model => model.OtherDetails, new { id="OtherDetails" })
       </td>
  </tr>
  <tr>
       <td>
            @Html.TextBoxFor(model => model.ContactID, new { id="ContactID" })
            @Html.ValidationMessageFor(model => model.ShipTo)
       </td>
  </tr>
  <tr>
       <td>
            @Html.TextBoxFor(model => model.ContactStreet, new { id = "ContactStreet" })
       </td>
       <td>
            @Html.TextBoxFor(model => model.ContactCity, new { id = "ContactCity" })
       </td>
       <td>
            @Html.TextBoxFor(model => model.ContactState, new { id = "ContactState" })
       </td>
  </tr>

</table>
<input type="submit" value="Submit" />
}

@section scriptContent
{
    <script src="@Url.Content("~/Scripts/jquery.validate.min.js")" type="text/javascript"></script>
    @*<script src="@Url.Content("~/Scripts/jquery.validate.unobtrusive.min.js")" type="text/javascript"></script>*@
    <script src="@Url.Content("~/Scripts/MicrosoftAjax.js")" type="text/javascript"></script>
    <script src="@Url.Content("~/Scripts/MicrosoftMvcValidation.js")" type="text/javascript"></script>
    <script type="text/javascript">
        $(document).ready(function () {
            $("form :input:enabled:visible:first").focus();
            $("form :input:enabled:visible:first").select();
            $(".input-validation-error").first().focus();
            $(".input-validation-error").first().select();
        });

        //THIS IS MY CURRENT CODE 
        $('#ContactID').change(function () {
            var ContactIDValue = $('#ContactID').val();

            $.ajax({
                url: '/Order/GetContactInformationForContactID/',
                type: 'POST',
                data: { ContactIDValue: ContactIDValue },
                success: function (result) { alert(result.STREET); }
                   //My database column is called STREET
            });
        });
    </script>
}

Model 模型

public class OrderViewModel
{
    public string OtherDetails { get; set; }
    public string ContactID { get; set; }
    public string ContactStreet { get; set; }
    public string ContactCity { get; set; }
    public string ContactState { get; set; }

}

Controller 调节器

[HttpGet]
public ActionResult Index()
{
    //private :)
}

[HttpPost]
public ActionResult Index(OrderViewModel)
{
    //private :)
}

[HttpPost]
public ActionResult GetContactInformationForContactID(string ContactIDValue )
{
    var result = myDB.CONTACTs.Where(r => r.CONTACTID == ContactIDValue ).FirstOrDefault();

    return Json(result );
}

How my code works now is when the user enters a ContactID, the page returns an alert. 我的代码现在的工作方式是当用户输入ContactID时,页面将返回警报。 The alert will display the STREET value from the database if there was a match. 如果匹配,警报将显示数据库中的STREET值。 If there was not a match, there will just be a blank alert box. 如果没有匹配项,将只有一个空白警报框。

I have tried giving each textbox an id and then using javascript to call them and then update them with the Json, but I have not had success with that. 我尝试给每个文本框指定一个ID,然后使用javascript调用它们,然后使用Json更新它们,但是我还没有成功。 How I tried that is shown here below. 我的尝试方式如下所示。 Perhaps I am doing it wrong? 也许我做错了吗?

$('#ContactStreet').Val = result.STREET;

I have tried messing with some partial views, but I must admit that I am not proficient with them and I am not sure if the model's integrity would be preserved. 我曾尝试弄乱一些局部视图,但是我必须承认我不精通它们,而且我不确定是否会保留模型的完整性。 I want to use the same model throughout if possible, but I am open to other solutions. 我希望尽可能使用相同的模型,但是我愿意接受其他解决方案。 If I end up needing two separate models, I would likely need both of them when the user clicks the submit button. 如果最终需要两个单独的模型,那么当用户单击“提交”按钮时,我可能会需要两个模型。

I look forward to some responses; 我期待一些回应; this has been a problem that has consumed my time over the past week. 在过去的一周中,这一直困扰着我。

Try $('#Street').Val(result.STREET); 尝试$('#Street').Val(result.STREET);

about Jquery .val() 关于Jquery .val()

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM