MVC - 将json结果发送到控制器,然后从控制器重定向

时间:2012-10-15 17:45:11

标签: knockout-mvc

成为MVC和淘汰赛的新手,我需要一些帮助。我试图将一些JSON结果(作为字符串)发布到我的控制器,然后将控制器RedirectToAction发送到新的视图和操作。

问题:即使命中了RedirectToAction,控制器也总是返回到相同的视图。

(它通过重定向代码,然后在最后返回到发布视图。)我不得不实施“下一步”动作,这有点令人尴尬。

另外:在发布帖子时,隐藏字段是存储/传递ID的最佳方式吗?

查看

@model WebRole.Website.Models.Registration3Model
@{
ViewBag.Title = "Step 3: Adding Members";
}
@using (Html.BeginForm())
{

<input name="GroupID" id="GroupID" type="hidden" value="@ViewData["GroupID"]" />      
<div id="Div1">
    <div class="5grid-layout">
        <div class="row">
            <div class="8u mobileUI-main-content">
                <!-- Content -->
                <div id="content">
                    <br />
                    <!-- Article -->
                    <article class="featured">
                        <header>
                            <h2>Registration</h2>
                            <span class="byline"></span>
                        </header>
                    </article>
                    <!-- Section -->
                    <div class="5grid grid-spaced">
                        <div class="row">
                            <section class="do-6u">
                                <h2>Step 3.</h2>
                                <p>
                                    You can add members to your group/family by selecting how the members will be notified (ex. Email, Cellphone) and the address/phone # of the member.
                                </p>
                                <p />
                                    <div id='contactsList'>
                                        <table class='contactsEditor'>
                                            <tbody data-bind="foreach: contacts">
                                                <tr>
                                                    <td>
                                                        <input type="radio" value="Email" data-bind="checked: contactType" />E-mail
                                                        <input type="radio" value="Voice" data-bind="checked: contactType" />Voice
                                                        <input type="radio" value="SMS" data-bind="checked: contactType" />SMS
                                                    </td>
                                                    <td>
                                                        <input data-bind='value: contactValue' size="40" />

                                                        <a href='#' data-bind='click: $root.removeContact'>Remove</a>
                                                    </td>               
                                                </tr>
                                            </tbody>
                                        </table>
                                        <input type="hidden" data-bind='value: lastSavedJson' />
                                        <a href='#' data-bind='click: addContact'>Add </a>
                                    </div>
                                <p />
                                <p>
                                    <button name="button" value="AddNewMember" data-bind='click: save, enable: contacts().length > 0'>Invite</button>

                                    <button name="button" value="Next">Finish</button>
                                </p>
                            </section>
                        </div>
                    </div>
                </div>
            </div>
        </div>
    </div>
</div>
}
    <script type="text/javascript">
        var initialData = [
        {
            contactValue: "",
            contactType: ""
        }
    ];

    var ContactsModel = function (contacts) {
        var self = this;
        self.contacts = ko.observableArray(ko.utils.arrayMap(contacts, function (contact) {
            return { contactValue: contact.firstName, contactType: contact.contactType };
        }));

        self.addContact = function () {
            self.contacts.push({
                contactValue: "",
                contactType: ""
            });
        };

        self.removeContact = function (contact) {
            self.contacts.remove(contact);
        };

        self.save = function () {
            self.lastSavedJson(JSON.stringify(ko.toJS(self.contacts), null, 2));
            var s = document.getElementById("GroupID").value
            $.ajax({
                url: "/Home/Add/",
                type: "POST",
                data: { jsonString: JSON.stringify(ko.toJS(self.contacts)), groupID: s },
                success: function (result) {
                },
                error: function (jqXHR, textStatus, errorThrown) {
                    var errorMessage = '';
                    $('#message').html(jqXHR.responseText);
                }
            });

        }; 


        self.lastSavedJson = ko.observable("")
    };

    ko.applyBindings(new ContactsModel(initialData));


</script>

MODEL:

public class Registration3Model
{
    public string GroupID { get; set; }

    // Success Message
    public string SuccessMessage { get; set; }

    public string jsonString { get; set; }
}

public class Registration4Model
{
    public string GroupID { get; set; }

    public Group SelectedGroup { get; set; }

    public Person Owner { get; set; }

    public List<ContactInfo> GroupContacts { get; set; }

    // Success Message
    public string SuccessMessage { get; set; }
}

控制器:

public class HomeController : Controller
{
    public class JsonCatch
    {
        public string groupID { get; set; }
        public string contactType { get; set; }
        public string contactValue { get; set; }
    }


    [AllowAnonymous]
    public ActionResult Registration3(Registration3Model model)
    {
        ViewData["GroupID"] = model.GroupID;
        return View("Registration3",  model);
    }

    [HttpPost]
    [ActionName("Add")]
    [AllowAnonymous]
    [AcceptVerbs(HttpVerbs.Post)]
    public ActionResult Add(string jsonString, string GroupID)
    {

    string s =GroupID;

        List<JsonCatch> j = JsonConvert.DeserializeObject<List<JsonCatch>>(jsonString);
        foreach (JsonCatch c in j)
        { 
            if (s != "")
            {

                // for member 1
                // 1. Add Person
                Person p = new Person();
                p.LastName = "";
                p.FirstName = "";
                p.PersonID = Guid.NewGuid();
                p.RowKey = p.PersonID.ToString();
                p.PartitionKey = "";
                p.Image = string.Format("../../Assets/Images/People/pic{0}.png", new Random().Next(1, 12));
                this.GetContext().InsertPerson(p);

                // 2. Add GroupMember
                GroupMember gm = new GroupMember();
                gm.RowKey = p.RowKey.ToString();
                gm.PartitionKey = s;
                gm.GroupMemberID = Guid.NewGuid();
                gm.TrustLevel = "Readonly";
                this.GetContext().InsertGroupMember(gm);

                // 3. Add ContactInfo
                ContactInfo ci = new ContactInfo();
                ci.PartitionKey = p.RowKey;
                ci.ContactInfoID = Guid.NewGuid();
                ci.RowKey = ci.ContactInfoID.ToString();
                ci.Type = c.contactType;
                ci.Value = c.contactValue;
                ci.UseToNotify = true;
                this.GetContext().InsertContactInfo(ci);

                // 4. Add Notification
                Notification n = new Notification();
                n.PartitionKey = "Invitation";
                n.NotificationID = Guid.NewGuid();
                n.RowKey = n.NotificationID.ToString();
                n.ContactType = c.contactType;
                n.ContactInfoValue = c.contactValue;
                n.NotificationType = "Invitation";
                n.PersonRowKey = p.RowKey;
                n.GroupRowKey = s;
                this.GetContext().InsertNotification(n);
            }
            }
        return View("Registration4", new { GroupID = s });
    }

            [AllowAnonymous]
    public ActionResult Registration4(Registration4Model model)
    {
        model.SelectedGroup = this.GetContext().GetGroup(model.GroupID);
        model.GroupContacts = model.SelectedGroup.GetContactInfoes(this.GetContext());
        model.Owner = model.SelectedGroup.GetOwner(this.GetContext());

        return View(model);
    }

            [HttpPost]
    [AllowAnonymous]
    [AcceptVerbs(HttpVerbs.Post)]
    [ActionName("Registration3")]
    [AcceptParameter(Name = "button", Value = "Next")]
    public ActionResult Registration3_Next(Registration4Model model)
    {
        return RedirectToAction("Registration4", new { GroupID = model.GroupID });
    }


    [HttpPost]
    [AllowAnonymous]
    [AcceptVerbs(HttpVerbs.Post)]
    [ActionName("Registration4")]
    [AcceptParameter(Name = "button", Value = "Continue")]
    public ActionResult Registration4_Continue(Registration4Model model)
    {
        return Redirect("~/AnotherWebsite.aspx");
    }

    #endregion
}

public class AcceptParameterAttribute : ActionMethodSelectorAttribute
{
    public string Name { get; set; }
    public string Value { get; set; }

    public override bool IsValidForRequest(ControllerContext controllerContext, MethodInfo methodInfo)
    {
        var req = controllerContext.RequestContext.HttpContext.Request;
        return req.Form[this.Name] == this.Value;
    }
}

1 个答案:

答案 0 :(得分:1)

问题是您使用Ajax调用Add方法,因此需要使用window.location = url更改为新视图。

您应该尝试返回一个带有GroupId的JsonResult,并在Ajax调用的 success 部分使用window.location并更改视图。

在模型外添加

 var newUrl="@Url.Action("Registration","Home")";

然后在你的模型中

 self.save = function () {
        self.lastSavedJson(JSON.stringify(ko.toJS(self.contacts), null, 2));
        var s = document.getElementById("GroupID").value
        $.ajax({
            url: "/Home/Add/",
            type: "POST",
            data: { jsonString: JSON.stringify(ko.toJS(self.contacts)), groupID: s },
            success: function (result) {
Code Change ----->  window.location=newUrl+"/"+result;
            },
            error: function (jqXHR, textStatus, errorThrown) {
                var errorMessage = '';
                $('#message').html(jqXHR.responseText);
            }
        });

    }; 

我假设控制器只返回Id。希望它有效。